I had a requirement where I had to create a file in my server folder through a PHP script.
Now, that's not as easy to implement in Linux as it is in Windows.
Trying to write a file in your server folder will give you "Permission Denied"; Even if you're logged in as root.
That's because PHP, which is trying to write the file, isn't running as root.
Follow the following steps to fix this issue:
That's because PHP, which is trying to write the file, isn't running as root.
Follow the following steps to fix this issue:
1. Find out PHP is being run as which user by running the following script:
<?php echo exec("whoami"); ?>
In Fedora, you get it as "apache."
( You might get it as "www-data" or something similar. )
This means that the user "apache" is running the PHP script.( You might get it as "www-data" or something similar. )
Hence, the user "apache" is trying to write the file in your server root folder, not "root".
Say, I have shifted my server root folder to "/home/sahay/newRoot".
So, "apache" should have WRITE access to this folder.
2. Check the permissions of "/home", and "/sahay" by running "ls -l".
By default "/home" has a 755 permission and the owner is "root".
Now, in Linux, a user is also treated as a group.
So, 755 here means "root", as a user, can READ, WRITE and EXECUTE in "/home".
Users part of the group "root" can READ and EXECUTE in "/home".
Any other user can READ and EXECUTE in "/home".
By default "/home/sahay" has a 700 permission and the owner is "sahay".
700 here means "sahay", as a user, can READ, WRITE and EXECUTE in "/home/sahay".
Users part of group "sahay" have no permissions.
Other users have no permissions.
3. Change the group permissions for "/home" and "/home/sahay" folders:
chmod 775 /home
chmod 770 /home/sahay
Now, any user which is part of the groups "root" and "sahay" will be able to READ, WRITE and EXECUTE in "/home" and "/home/sahay"
4. Add "apache" to the groups "root" and "sahay":
usermod -aG root apache
usermod -aG sahay apache
"a" is used to append the list of groups the user already is in. Without "a" it will overwrite the existing group.
Since, "apache" is part of "root" and "sahay" group, it will have access to READ, WRITE and EXECUTE on"/home" and "/home/sahay" respectively.
5. If you've got SELinux installed, edit the following the SELinux Config file like this:
SELINUX=disabled
In Fedora, it is stored in "/etc/selinux/config"
This would require a restart after everything is done.
Finally, you're good to go. Now you'll be able to use function like file_put_contents() etc. on your server root folder.
Finally, you're good to go. Now you'll be able to use function like file_put_contents() etc. on your server root folder.
No comments:
Post a Comment