如何在文本区域的下拉列表中编辑所选文件,然后保存它


How to edit selected file in a dropdown list in textarea and then save it?

我有这样的脚本,我们称这个页面为select.php

<?php
........
echo '
<form action="editor.php" method="post">
<select name="file">
  <option value="volvo">Volvo.txt</option>
  <option value="saab">Saab.txt</option>
  <option value="mercedes">Mercedes.txt</option>
  <option value="audi">Audi.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>';
.........
?>

我想在另一个名为编辑器的页面中编辑所选文件.php然后保存它,如何将所选文件的value传递给编辑器.php然后在textarea中对其进行编辑?

首先,为了使事情更简单,我将更改您的表单,以便它传递实际的文件名,而不仅仅是它的简短版本:

<form action="editor.php" method="post">
<select name="file">
  <option value="Volvo.txt">Volvo.txt</option>
  <option value="Saab.txt">Saab.txt</option>
  <option value="Mercedes.txt">Mercedes.txt</option>
  <option value="Audi.txt">Audi.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>

接下来,编辑.php

请注意:在此处使用白名单! 这就是 $allowed_files。您不希望用户能够编辑他们想要的系统上的任何文件。永远不要相信用户输入!(虽然真的,从安全的角度来看,这整个想法让我真的很不舒服。我希望这不是一个可公开访问的脚本。

<?php
$allowed_files = ["Volvo.txt","Saab.txt","Mercedes.txt","Audi.txt"];
if(!empty($_POST)){
    if(in_array($_POST["file"], $allowed_files)){
        $file_contents = file_get_contents($_POST["file"]);
    }
}
if($file_contents !== false){
    echo '
        <form method="post" action="save_file.php">
        <input type="hidden" name="file" value="' . $_POST["file"] . '">
        <textarea name="file_contents">$file_contents</textarea>
        <input type="submit" value="Save file">
        </form>
    ';
}else{
    echo 'File could not be opened.';
}

然后你只需要弄清楚如何处理save_file.php 这将接收 $_POST["file"] 中的文件名(您绝对 100% 肯定需要再次根据白名单进行验证!),并且它将接收 $_POST["file_contents"] 中的文件内容。

祝你好运!

您可以使用 PHP Open File - fopen()。

 <form action="editor.php" method="post">
<select name="file">
  <option value="volvo">Volvo.txt</option>
  <option value="saab">Saab.txt</option>
  <option value="mercedes">Mercedes.txt</option>
  <option value="audi">Audi.txt</option>
</select>
<textarea></textarea>
<input type="submit" name="edit" value="Edit" />
</form>

 if(isset($_POST["edit"])) {
   $filename = $_POST["file"];
   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
<textarea>if(isset($filecontent)) { echo $filecontent; }</textarea> //echos file content in textarea.
 //write to text file
 if(isset($_POST["update"])) {
   $myfile = fopen("$files", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
 }

试试这个将值传递给文本编辑器(编辑器.php)...

if(isset($_POST['edit']))
{
    echo "<textarea>".$_POST['file']."</textarea>";
}

这只导致没有扩展名的文件名,如果要包含扩展名,则需要在每个<option>的值中添加.txt