首页 > 解决方案 > 将文本保存到 html 服务器上的 txt 文件?

问题描述

我正在建立一个小型网站,我遇到了一个问题,我想在按下按钮时将硬编码的数字保存到 .txt 文件中。

我已经在其他网站上尝试了一些在线示例,但是我唯一一次可以做同样的事情是当我使用 php 并且它不是在按下按钮时

                ...
                <br>
                <br><table id="tblCustomers" style="width: 100%;">
                    <tr>
                        <td style="width: 50%;">
                        <button onclick="location.href='{% url 'script' 
                         %}'">Execute Script</button> <hr>
                             //On this button it should save a 23 to a txt 
                               file wich is in the same folder and has the 
                               name contacts.txt                 
                        </td>
                        <td style="width: 50%;"><input type="button" 
                         id="btnread" value="Count Rows" /></td>
                    </tr>
                </table>
                ...

这是我尝试过的其他东西,它不起作用。

标签: javascriptphphtml

解决方案


您不能使用 Javascript 直接写入文件 - 能够这样做的安全隐患不值得考虑。您可以做的是(或其中之一)将使用 Javascript 发送请求以将数据保存到后端脚本,该脚本确实有权访问并能够写入服务器上的文件。

例如 - 使用fetchapi 向 PHP 脚本发送请求(它与这里的演示文档相同,但可能是完全不同的脚本) - PHP 代码处理获取请求并执行两个任务之一 - 要么将数据写入在发送 fetch 回调的响应以进行处理/播放之前,文件或从中读取。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        $file='test-contacts.txt';  #   write to this file
        $json=json_decode( file_get_contents( 'php://input' ) );    #   get the request body

        $action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
        $value=!empty( $json ) && property_exists( $json, 'value') ? $json->value : false;


        switch( $action ){
            case 'execute':
                $data = array( 'bytes'=>file_put_contents( $file, $value . PHP_EOL, FILE_APPEND ), 'value'=>$value, 'time'=>time() );
            break;
            case 'count':
                $data=array( 'bytes'=>filesize( $file ), 'time'=>time(), 'count'=>sizeof( file( $file ) ) );
            break;
            default:
                http_response_code( 400 );
                exit( json_encode('error') );
        }

        http_response_code( 200 );
        header('Content-Type: application/json');
        exit( json_encode( $data ) );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script>
            document.addEventListener('DOMContentLoaded',()=>{
                /* find and assign event handler to the buttons */
                Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
                    bttn.addEventListener('click',function(e){
                        /* prepare the Fetch request */
                        let url=location.href;
                        let options={ 
                            method:'post',
                            headers:{ 'Content-Type':'application/json' },
                            body:JSON.stringify({ 
                                action:this.name,
                                value:23 /* seems very peculiar hard-coding a value to be written to file!!! */
                            })
                        };
                        /* The callback to process returned JSON data */
                        const callback=function( json ){
                            let out=document.querySelector( 'output' );
                                out.innerHTML='';
                            Object.keys( json ).map( k=>{
                                let div=document.createElement('div')
                                    div.innerText=[k,json[k]].join('=');
                                out.appendChild( div );
                            });                     
                        };
                        /* If there are errors... */
                        const errorcallback=function(err){
                            alert( err )
                        };
                        /* Send the request and manipulate the response */
                        fetch( url, options )   
                            .then( r=>{ return r.json() })
                            .then( callback )
                            .catch( errorcallback );
                    });
                })
            });
        </script>
    </head>
    <body>
        <table id='tblCustomers'>
            <tr>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
            </tr>
        </table>
        <output></output>
    </body>
</html>

如果尝试记录不同的值(如评论所建议的那样),建议对数据结构进行细微更改,以便可以正确记录每个 ID。然而,我对数据库所做的评论仍然有效,但也许以下内容可能有用。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        $file='test-contacts.txt';  #   write to this file
        $json=json_decode( file_get_contents( 'php://input' ) );    #   get the request body

        $action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
        $value=!empty( $json ) && property_exists( $json, 'value') ? intval( $json->value ) : false;


        $data=file_exists( $file ) ? json_decode( file_get_contents( $file ) ) : new stdclass;

        switch( $action ){

            case 'execute':
                $data->$value=isset( $value ) && isset( $data->$value ) ? $data->$value + 1 : 1;
                file_put_contents( $file, json_encode( $data ) );
            break;

            case 'count':
                $value=isset( $data->$value ) ? $data->$value : 0;
                $data=new stdclass;
                $data->count=$value;
            break;

            default:
                http_response_code( 400 );
                exit( json_encode('error') );
        }

        http_response_code( 200 );
        header('Content-Type: application/json');
        exit( json_encode( $data ) );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script>
            document.addEventListener('DOMContentLoaded',()=>{
                /* find and assign event handler to the buttons */
                Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
                    bttn.addEventListener('click',function(e){
                        /* prepare the Fetch request */
                        let url=location.href;
                        let options={ 
                            method:'post',
                            headers:{ 'Content-Type':'application/json' },
                            body:JSON.stringify({ 
                                action:this.name,
                                value:this.parentNode.parentNode.dataset.id
                            })
                        };
                        /* The callback to process returned JSON data */
                        const callback=function( json ){
                            let out=document.querySelector( 'output' );
                                if( out ) out.innerHTML='';

                            Object.keys( json ).map( k=>{
                                let div=document.createElement('div')
                                    div.innerText=[ k, json[ k ] ].join('=');
                                out.appendChild( div );
                            });                     
                        };
                        /* If there are errors... */
                        const errorcallback=function(err){
                            alert( err )
                        };
                        /* Send the request and manipulate the response */
                        fetch( url, options )   
                            .then( response => { return response.json() } )
                            .then( callback )
                            .catch( errorcallback );
                    });
                })
            });
        </script>
    </head>
    <body>
        <table id='tblCustomers'>
            <tr data-id=23>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
            </tr>

            <tr data-id=24>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
            </tr>

            <tr data-id=25>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
            </tr>

            <tr data-id=26>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
            </tr>
        </table>
        <output></output>
    </body>
</html>

删除条目或删除整个内容可以这样完成:

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        $file='test-contacts.txt';  #   write to this file
        $json=json_decode( file_get_contents( 'php://input' ) );    #   get the request body

        $action=!empty( $json ) && property_exists( $json, 'action') ? $json->action : false;
        $value=!empty( $json ) && property_exists( $json, 'value') ? intval( $json->value ) : false;


        $data=file_exists( $file ) ? json_decode( file_get_contents( $file ) ) : new stdclass;

        switch( $action ){

            case 'execute':
                $data->$value=isset( $value ) && isset( $data->$value ) ? $data->$value + 1 : 1;
                file_put_contents( $file, json_encode( $data ) );
            break;

            case 'count':
                $value=isset( $data->$value ) ? $data->$value : 0;
                $data=new stdclass;
                $data->count=$value;
            break;

            case 'clear':
                $data=unlink( $file );
            break;

            case 'delete':
                if( property_exists( $data, $value ) && !empty( $data->$value ) ){
                    unset( $data->$value );
                    file_put_contents( $file, json_encode( $data ) );
                }
            break;

            default:
                http_response_code( 400 );
                exit( json_encode('error') );
        }

        http_response_code( 200 );
        header('Content-Type: application/json');
        exit( json_encode( $data ) );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script>
            document.addEventListener('DOMContentLoaded',()=>{
                /* find and assign event handler to the buttons */
                Array.from( document.querySelectorAll('td > input[ type="button" ]') ).forEach( bttn=>{
                    bttn.addEventListener('click',function(e){
                        /* prepare the Fetch request */
                        let url=location.href;
                        let options={ 
                            method:'post',
                            headers:{ 'Content-Type':'application/json' },
                            body:JSON.stringify({ 
                                action:this.name,
                                value:this.parentNode.parentNode.dataset.id
                            })
                        };
                        /* The callback to process returned JSON data */
                        const callback=function( json ){
                            let out=document.querySelector( 'output' );
                                if( out ) out.innerHTML='';

                            Object.keys( json ).map( k=>{
                                let div=document.createElement('div')
                                    div.innerText=[ k, json[ k ] ].join('=');
                                out.appendChild( div );
                            });                     
                        };
                        /* If there are errors... */
                        const errorcallback=function(err){
                            alert( err )
                        };
                        /* Send the request and manipulate the response */
                        fetch( url, options )   
                            .then( response => { return response.json() } )
                            .then( callback )
                            .catch( errorcallback );
                    });
                })
            });
        </script>
    </head>
    <body>
        <table id='tblCustomers'>
            <tr data-id=23>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
                <td><input type='button' name='delete' value='Delete record' /></td>
                <td><input type='button' name='clear' value='Clear file' /></td>
            </tr>

            <tr data-id=24>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
                <td><input type='button' name='delete' value='Delete record' /></td>
                <td><input type='button' name='clear' value='Clear file' /></td>
            </tr>

            <tr data-id=25>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
                <td><input type='button' name='delete' value='Delete record' /></td>
                <td><input type='button' name='clear' value='Clear file' /></td>
            </tr>

            <tr data-id=26>
                <td><input type='button' name='execute' value='Execute Script' /></td>
                <td><input type='button' name='count' value='Count Rows' /></td>
                <td><input type='button' name='delete' value='Delete record' /></td>
                <td><input type='button' name='clear' value='Clear file' /></td>
            </tr>
        </table>
        <output></output>
    </body>
</html>

推荐阅读