用fopen($ file,'w')打开的文件不可写

使用 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>
asas8520 回答:用fopen($ file,'w')打开的文件不可写

永远不要将chmod文件归档到777。甚至不是暂时的。这是一种安全风险,在正确设置的服务器上不需要使用它。

如果PHP无法写入文件,则意味着Web服务器不是文件的所有者,或者您以某种方式从所有者那里以root /管理员身份撤消了写入权限。验证相关文件的所有者。如果您将Apache用作Web服务器,则所有者可能应该是www-data之类的东西。如果不是正确的所有者,请确保通过更改所有者来解决该问题。

请记住,如果您已设置apache服务多个域,则所有者可能大不相同,例如client1client2等。

确定设置了正确的所有者后,将文件更改为755就足够了。

本文链接:https://www.f2er.com/2787493.html

大家都在问