在PHP中,why won';t将此写入test.txt


In PHP, why won't this write to test.txt?

我的代码是

<?php
$fp = fopen('test.txt', "a+");
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>

但是test.txt仍然为空。我没有看到任何错误,我不明白为什么它没有写出来。

将其写入控制台

chmod a+w test.txt 

这是一个文件权限问题。

这将把你的文件修改为777,使其可写。

在Linux服务器上测试:

<?php
$fp = fopen('test.txt', "a+");
chmod("test.txt", 0777); // try also 0666 or 0644
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>

您也可以使用06660644,这取决于您希望文件具有多高的权限,但0644将是您最安全的选择;请参见下文。

您也可以通过FTP键入chmod 777 test.txtchmod 666 test.txtchmod 644 test.txt

我的服务器让我使用0644来编写和附加代码,在您想要执行代码的服务器上可能会有所不同。


引用自http://www.centos.org/docs/2/rhl-gsg-en-7.2/s1-navigating-chmodnum.html

小心666和777

将权限设置为666或777将允许每个人读取和写入文件或目录。

这些权限可能允许篡改敏感文件,因此通常情况下,使用这些设置不是一个好主意。

以下是一些常见设置、数值及其含义的列表:

-rw------- (600) — Only the owner has read and write permissions.
-rw-r--r-- (644) — Only the owner has read and write permissions; the group and others can read only.
-rwx------ (700) — Only the owner has read, write and execute permissions.
-rwxr-xr-x (755) — The owner has read, write and execute permissions; the group and others can only read and execute.
-rwx--x--x (711) — The owner has read, write and execute permissions; the group and others can only execute.
-rw-rw-rw- (666) — Everyone can read and write to the file. (Be careful with these permissions.)
-rwxrwxrwx (777) — Everyone can read, write and execute. (Again, this permissions setting can be hazardous.) 

以下是目录的一些常见设置:

drwx------ (700) — Only the user can read, write in this directory.
drwxr-xr-x (755) — Everyone can read the directory, but its contents can only be changed by the user.