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

2019-09-02 02:58发布

问题:

My code is

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

but test.txt is still empty. I don't see anything wrong and I don't understand why it's not writing.

回答1:

Write this in a console

chmod a+w test.txt 


回答2:

This is a file permissions issue.

This will chmod your file to 777 making it writeable.

Tested on Linux server:

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

You can also use 0666 or 0644 depending on how high a permission you wish the file to have, yet 0644 would be your safest option; see below.

You can also type in chmod 777 test.txt or chmod 666 test.txt or chmod 644 test.txt via FTP.

My server let's me use 0644 to write and append to and may be different on the server you are wanting to execute your code.


Quoted from http://www.centos.org/docs/2/rhl-gsg-en-7.2/s1-navigating-chmodnum.html

Beware 666 and 777

Setting permissions to 666 or 777 will allow everyone to read and write to a file or directory.

These permissions could allow tampering with sensitive files, so in general, it is not a good idea to use these settings.

Here is a list of some common settings, numerical values and their meanings:

-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.) 

Here are some common settings for directories:

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. 


标签: php file fwrite