使用HTML表单用PHP重写文件


Rewrite a file with PHP using HTML form

所以我正在开发一个小php文件,该文件应该为用户更改特定的文件。它获取文件的内容,并将其放入表单中的文本区域。我如何才能做到这一点,以便在该文本区域内进行的任何编辑都会被重写到服务器上的文件中?更好的是,我可以允许用户只编辑某些行,并且只重写这些行吗?

到目前为止,这是我的代码:

<?php
$filename = "../tree_c/index.php";
//$fp = fopen ($filename, "w"); <- doesn't seem to work for it opens empty file.
$contents = file_get_contents($filename);
/*
if (isset($_POST['field'])) {
    // something here to rewrite the file.
*/
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <textarea name="field"><?php echo $contents ?></textarea>
    <input type="submit" value="Save">
</form>

这应该很容易实现:

if (isset($_POST['field'])) {
  file_put_contents($filename, $_POST['field']);
}
        $datafile = "Files.txt";
        $fp = fopen($datafile, "r");
        $textdata= fgets($fp, 1024);
        $text = '"'.$textdata.'"';
        $this->set('text',$text);
        if(!empty($this->data))
        {
           $datas = $this->data['data']['text'];  //(your Textarea name)
           $myFile = "Files.txt";
           $fh = fopen($myFile, 'w') or die("can't open file");
           fwrite($fh, $datas);
           fclose($fh);
        }

希望这对你有帮助。。。。