【发布时间】:2020-04-28 15:51:29
【问题描述】:
使用 fopen($file, 'w') 将文本文件加载到表单中,但该文件不可写入且无法保存更改。显然是权限问题,但出于明显的安全原因,我不想将它们更改为 777。有没有办法即时执行,然后在保存后将其更改回来?
<?php $file = "$ServerRoot/text/test.txt";
// $ServerRoot is defined elsewhere and is to the root of the filesystem
// Retrieve the submitted changes and save to the file
if ($_SERVER['REQUEST_METHOD'] === "POST") :
$fh = fopen($file, 'w') or die("Can't open file for writing.");
fwrite($fh, $_POST['textfield']);
fclose($fh);
echo "Content saved.";
endif;
// FOR DIAGNOSTIC PURPOSES ONLY
$TestFile = (file_exists($file)) ? "The file exists\n" : "The file does <font color=\"red\">NOT</font> exist\n";
$TestFile .= (is_readable($file)) ? "The file is readable\n" : "The file is <font color=\"red\">NOT</font> readable\n";
$TestFile .= (is_writable($file)) ? "The file is writable\n" : "The file is <font color=\"red\">NOT</font> writable\n";
$TestFile = nl2br($TestFile);
// Read the textfile
$text = file_get_contents($file);?>
<div align="center">
<?=$TestFile;?>
<form action="<?=$submitFormAction;?>" method="post">
<div><input type="submit" value="Save File" />
<input type="reset" value="Reset"/></div>
<div><textarea name="textfield" rows="25" cols="85"><?=htmlspecialchars($text);?></textarea></div>
<div><input type="submit" value="Save File" />
<input type="reset" value="Reset"/></div>
</form>
</div>
【问题讨论】:
-
网络服务器用户应该是您服务器中文件/目录的所有者。这样你就不必 chmod 文件了。如果您是服务器所有者,则应确保这一点。如果没有,您应该责骂您的服务器提供商不这样做! - 另外,回答您的问题:不,如果 PHP 首先没有写入文件的权限,您不能在 PHP 中使用更多权限对文件进行 chmod。
-
到目前为止,这只是在我的开发系统上离线,并且文件应该全部归网络服务器所有。我会检查的。
-
好吧,如果你确定网络服务器用户是所有者,chmodding 到 755 就足够了
-
@icecub 你是对的,这些文件归我所有,而不是网络服务器!在我看来(现在我想到了),当它在几年前设置时,这是我能够移动、复制或保存文件并打开文件以使用桌面应用程序编辑它们的唯一方法。我会尝试改回来。实时服务器不应该有这个限制,但是在开发中测试它还为时过早,因为这个表单还没有任何身份验证。
-
我强烈建议您查看ISPConfig 3。它是完全免费的,他们有关于如何为自己设置整个(测试)服务器的完整教程。这需要一些工作,但一旦你完成了这一切,你将拥有一个非常易于管理的服务器来满足你所需要的一切。
标签: php file-permissions fopen