Search code examples
phpfile-get-contentschmodopen-basedir

PHP Chmod Problem Creating files


I've got the following situation:

public_html - 755

=> avatar - 777

=> poll - 755

Now when I use the following code, i'll get an error (Warning: file_put_contents(../test.php) [function.file-put-contents]: failed to open stream: Permission denied in XXX):

<?php
file_put_contents('../test.php','<?php');
?>

But when I use the code below, it'll work just fine:

<?php
file_put_contents('test.php','<?php');
?>

(both executed from 'avatar', with 0777)

How can I solve this?


Solution

  • Since your script is executing from avatar, which has 0777 permission (world read/write/execute), it is normal that you are able to create a file within it (i.e.: file_put_contents("test.php")).

    If you are not able to create files in public_html (i.e.: file_put_contents("../test.php")), it's because the user that is executing your script (most probably the Apache user) is not the owner of public_html (the owner is most probably a FTP user). Because 0755 means that only the owner is able to write to the directory, then others are only able to read or execute from it.

    If you have shell access, you can use chown to change the owner of the file:

    bash-4.1.5$ chown newuser public_html
    

    Or you can chmod with higher permissions for non-owners, but you ought to be careful with that.