Проблемы с записью обратно в текстовый файл с использованием PHP fwrite из файла, выбранного из выпадающей формы - PullRequest
1 голос
/ 15 февраля 2020

У меня проблемы с записью обратно в текстовый файл, выбранный из формы html с раскрывающимся меню, скрипт может читать, но не может записать обратно, возвращает «Невозможно открыть файл» .using PHP fopen и fwrite

Это индекс. 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>

И это функция. 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>

Ответы [ 2 ]

0 голосов
/ 15 февраля 2020

Вы не отправляете имя файла во второй форме, просто код, поэтому $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>
0 голосов
/ 15 февраля 2020

Пожалуйста, проверьте разрешение целевого файла и папка в этом файле должна быть.

...