无法使用 PHP fwrite 从下拉列表中选择的文件写回文本文件

Trouble Writing back to text file using PHP fwrite from file selected from a dropdown form

我无法回写从带有下拉菜单的 html 表单中选择的文本文件,脚本可以读取但无法回写,returns "Unable to Open File".使用 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>

请检查目标文件的权限以及文件所在的文件夹。

您没有以第二种形式发送文件名,只是代码,因此,$filename 未定义。将其添加到隐藏的输入中:

global $variable; 在这里没有用,因为在处理表单时,变量将不会在下一个脚本执行时出现。

<?php

// Default value for contents:
$filecontent = '';

// Ok, read the file here
if(isset($_POST["edit"])) {
   $filename = $_POST["list"];

   global $filename; // This will not be useful

   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
// If request comes from second form, process it
if(isset($_POST['update'])) {
   // Get file name from input hidden
   $filename = $_POST["filename"];

   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
   // End the script, no need to show the form again
   die('File updated successfully.');
}
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<input type="hidden" name="filename" value ="<?php
    // Send filename within form
    echo $filename;
?>">
<textarea name="textareaContent" rows="50" cols="100">
<?
// No if needed here, we already have a value
echo $filecontent;
?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />

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