如何使用PHP编辑/更新文本文件

11

在阅读了许多有关编辑/更新文件功能的类似问题后,我发现这些方法都无效,因此希望得到一些帮助。

我正在尝试从php中编辑一个.txt文档。 我已经尝试了以下几种方法:

  1. This was the last code which I've read here and didn't work.

    $data_to_write = "$_POST[subject]";
    $file_path = "text/" + $row['name'];
    $file_handle = fopen($file_path, 'w'); 
    fwrite($file_handle, $data_to_write);
    fclose($file_handle);
    
  2. And this is my previous try:

    $new_contents = "$_POST[subject]\n";
    $path = "text/$row[name]";
    file_put_contents($path, $new_contents);
    

我希望有人可以向我解释如何正确地完成这个操作。谢谢。

以下是我的所有代码:

<?php
if(isset($_GET['id']))
{
$edit = mysql_query("SELECT * FROM text_area WHERE text_id=$_GET[id]");
$row = mysql_fetch_assoc($edit);
$contents = file_get_contents($row['content']);
?>
<form action="" name="form" method="post">
<input type="hidden" name="id" value="<?php echo $row['text_id']; ?>" /><br />
<label for="">Заглавие:</label><br />
<input type="text" name="title" style="width:500px;" value="<?php echo $row['subject'] ?>" /><br />
<select name="opt">
<option value="0"></option>
<?php

$result = mysql_query("SELECT * FROM image_area");
while ($row = mysql_fetch_array($result))
{
        echo "<option value=" . $row['path'] . ">" . $row['name'] . "</option>
            ";  
    }

?>
</select><input type="button" name="sumbitP" value="Choose" onclick="addtext();" /><a href="../image_list.php" target="_blank">Image list</a><br />
<textarea rows="10" cols="50" name="text" id="markItUp"><?php echo $contents ?></textarea><br />
<input type="submit" name="sumbitT" value="Update" />
<input type="reset" value="Reset" />

</form>
<?php
}
?>
<?php

if(isset($_POST['id']))
{
    if(mysql_query("UPDATE text_area SET title='$_POST[subject]' WHERE text_id ='$_POST[id]'"))
    {

$data_to_write = "" . $_POST['text'];
$file_path = "text/$row[name]";
$file_handle = fopen($file_path, 'w');
fwrite($file_handle, $data_to_write);
fclose($file_handle);

        echo '<br><br><p align="center">Everything is ok</p>';
    } else {
        echo '<br><br><p align="center">Everything is not ok</p>' ;
    }
?>

我想补充一些可能有用的东西:
我遇到了这个错误,但是在谷歌上找不到答案。
警告:fopen(text /)[function.fopen]:无法打开流:是目录


在您的代码顶部使用 ini_set('display_errors', 1);error_reporting(E_ALL);,这样错误信息将会显示出来,您可以看到为什么它不起作用。 - Matt
你可能已经做得很对了,但可能没有权限。请参考https://dev59.com/ymDVa4cB1Zd3GeqPeIap。希望能帮到你。 - Akshaya Shanbhogue
我已将文件夹的权限设置为777,因为我想看看它是否工作,但仍然没有。 - Mr Andreev
6个回答

7
您可以使用fopen()以附加模式打开文件,并将任何内容放在末尾,例如:
$path = dirname(__FILE__).'/newfile.txt';
$fp = fopen($path, 'a');
if(!$fp){
echo 'file is not opend';
}
fwrite($fp, 'this is simple text written');
fclose($fp);

7
您只需要更改以下内容:
$file_path = "text/" + $row['name'];

转换成:

$file_path = "text/" . $row['name'];

PHP中的字符串连接运算符是 . (而不是+)。

确保目录text存在,否则最好先检查再写入:

$data_to_write = $_POST['subject'];
$file_path = "text/" . $row['name'];

if ( !file_exists("text") )
    mkdir("text");

$file_handle = fopen($file_path, 'w'); 
fwrite($file_handle, $data_to_write);
fclose($file_handle);

出现了以下错误: 警告:fopen(text/) [function.fopen]:在edit.php的第120行打开流失败:是一个目录警告:fwrite():在edit.php的第121行提供的参数不是有效的流资源警告:fclose():在edit.php的第122行提供的参数不是有效的流资源 - Mr Andreev
你的 $row['name'] 结果为空白。请检查一下。 - Nikhil Patel
我刚决定使用它以便于文档管理。在数据库中,主题和内容已经存在,并且在主题上有指向文档的路径,所以我决定也尝试使用一个名称。那么我应该删除什么? - Mr Andreev
你是说 $_POST['subject'] 是文档的路径?请展示你完整的代码,这样会更有帮助。 - Nikhil Patel

5
您需要使用file_get_contents来获取您的文件文本。
$file_path= "text/" . $row['name'];
// Open the file to get existing content
$current = file_get_contents($file_path);
// Append a new person to the file


$data_to_write.= $_POST[subject]."\n";
// Write the contents back to the file
file_put_contents($file_path, $data_to_write);

请参阅 文档

我已经在文档的前面定义了file_get_content,所以我可以获取信息并将其显示在文本区域中。 - Mr Andreev

2

我更喜欢使用file_put_contents,并设置标志以添加文本而不是覆盖整个文件。通过使用标志,您还可以在同时访问同一文件的多个脚本中锁定文件。

下面是实现方法:

$file_name = 'text.txt';
$line= "This is a new line\n";
 
// use flag FILE_APPEND to append the content to the end of the file
// use flag LOCK_EX to prevent other scripts to write to the file while we are writing
file_put_contents($file_name , $line, FILE_APPEND | LOCK_EX);

这里是完整的文档:https://www.php.net/manual/zh/function.file-put-contents.php

0

我认为问题可能出在第一行:

$data_to_write = "$_POST[subject]";

将其替换为以下内容:
$data_to_write = "" . $_POST['subject'];

我强烈建议使用hmtlentities或其他方式来保护它,因为这是直接用户输入的。


它不能只是这样吗:$data_to_write = $_POST['subject']; - Loko
通常在输入变量后附加一个空字符串的原因是,使代码能够处理输入变量未定义的情况。 - MarkHu

0

我刚把代码放进编译器,你漏掉了一个}在结尾处。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接