用于编辑文件的表单


PHP: form for editing files

我用PHP创建了一个小文件管理器。一切正常,读取,删除,移动,编辑。但是在显示要修改的文件内容时,出现了一个问题。

在之前的表单中,我让用户选择要修改的文件,在另一个页面中,我获得文件名,并在文本区域中显示其内容,代码如下:

<?php
if (isset($_POST['file'])) {
    $file = $_POST['file'];
?>
<form action="edit_file_process3.php" method="get">
    <p>This is the content of the file <?php echo $file; ?>. Now you can modify it:</p>
<textarea rows="10" cols="70" name="content"><?php readfile($file)   ?></textarea>
<p><input type="submit" name="submit" value="edit <?php echo $file; ?>" /> </p>
</form>
<a href="read2.php">Come back to the file manager</a>

我第一次选择一个文件,在文本区而不是它的正确内容,它看起来像这样:

<br />
<font size='1'><table class='xdebug-error xe-warning xe-scream' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> SCREAM: Error suppression ignored for</th></tr>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Warning: readfile(prova4.txt): failed to open stream: No such file or directory in C:'wamp'www'LEARNING'Files'edit_file_process3.php on line <i>50</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0004</td><td bgcolor='#eeeeec' align='right'>144848</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:'wamp'www'LEARNING'Files'edit_file_process3.php' bgcolor='#eeeeec'>..'edit_file_process3.php<b>:</b>0</td></tr>
<tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0004</td><td bgcolor='#eeeeec' align='right'>145248</td><td bgcolor='#eeeeec'><a href='http://www.php.net/readfile' target='_new'>readfile</a>
(  )</td><td title='C:'wamp'www'LEARNING'Files'edit_file_process3.php' bgcolor='#eeeeec'>..'edit_file_process3.php<b>:</b>50</td></tr>
</table></font>

如果我用其他内容覆盖该文本,那么它就会工作,并且下一次,文本区域将显示文件的适当内容。但它第一次这么做是相当令人讨厌的。为什么会发生这种情况?

您必须确保脚本在正确的目录中查找文件。

可以使用绝对路径。/from/root/to/my/dir或相对路径。../where/is/my/file .

如果您使用的是相对路径,您必须有正确的路径相对于脚本查找文件。否则,您将得到提示打开流失败:没有这样的文件或目录,如在本例中。

编辑

如果我没理解错的话,你是在编辑一个文件系统中已经存在的文件。当你第一次尝试打开它时,你会得到你所描述的错误。这是因为脚本在错误的目录中查找文件。当你"编辑"并保存它时,就像Barmar指出的那样,你很可能实际上是在另一个目录中创建了一个新文件。在此之后,您可能有两个不同的文件存在于不同的目录中,但名称相同。另一个是在文件资源管理器中显示的另一个是你实际编辑的