P粉3767388752023-08-28 09:42:11
Step 1: Identify PHP User
Create a PHP file with the following content:
<?php echo `whoami`; ?>
Upload it to your web server. The output should resemble the following:
www-data
Therefore, the PHP user is www-data
.
Step 2: Determine the directory owner
Next, check the details of the web directory via the command line:
ls -dl /var/www/example.com/public_html/example-folder
The result should look similar to the following:
drwxrwxr-x 2 exampleuser1 exampleuser2 4096 Mar 29 16:34 example-folder
Therefore, the owner of this directory is exampleuser1
.
Step 3: Change directory owner to PHP user
Then, change the owner of the web directory to the PHP user:
sudo chown -R www-data /var/www/example.com/public_html/example-folder
Verify that the owner of the web directory has changed:
ls -dl /var/www/example.com/public_html/example-folder
The result should look similar to the following:
drwxrwxr-x 2 www-data exampleuser2 4096 Mar 29 16:34 example-folder
At this point, the owner of example-folder
has been successfully changed to the PHP user: www-data
.
Finish! PHP should now be able to write to the directory.
P粉3524080382023-08-28 09:07:16
A simple way is to have PHP create the directory itself first.
<?php $dir = 'myDir'; // create new directory with 744 permissions if it does not exist yet // owner will be the user/group the PHP script is run under if ( !file_exists($dir) ) { mkdir ($dir, 0744); } file_put_contents ($dir.'/test.txt', 'Hello File');
This can save you trouble with permissions.