首页 > 解决方案 > 使用 PHP fwrite 从下拉表单中选择的文件中写回文本文件时遇到问题

问题描述

我无法用下拉菜单写回从 html 表单中选择的文本文件,脚本能够读取但无法写回,返回“无法打开文件”。使用 PHP fopen 和 fwrite

这是 index.html 代码:

<html>
<head></head>
<title>Edit Server Side Text Files</title>
<body>
<form action="function.php" method="post">
<select name="list">
  <option value="./files/banned-kdf.txt">banned-kdf.txt</option>
  <option value="./files/blackList.txt">blackList.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>
</body>
</html>

这是function.php代码:

<?php

if(isset($_POST["edit"])) {
   $filename = $_POST["list"];
   global $filename;
//   var_dump($filename);
   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<textarea name="textareaContent" rows="50" cols="100">
<?

if(isset($filecontent)) { echo $filecontent; }

?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />
 </textarea>
<?
//write to text file
 if(isset($_POST["update"])) {
// The following two lines are just for troubleshooting and have been commented out.     
//   echo $_POST["update"];
//   var_dump($filename);
   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
 }
 ?>

 </form>
 <br>
 <br>
<a href="/index.html">Return to List Selection</a>
</html>

标签: phphtmlformsfopenfwrite

解决方案


请检查目标文件的权限以及该文件应该位于的文件夹。


推荐阅读