I currently have a php script that is running when a browser browser browses to the webpage. What I'm trying to do is write a text file when the script runs that stores a variable. The owner of the folder is apache, but everyone has read write, strictly for testing purposes. (I thought it might be a permissions issue) SELINUX is enabled on the server, and when I run the script from console it creates the text file just fine, and in the right directory.
file_put_contents("My working file location", $myString);
I'm using this line to try to write and create the text file, I know that my file location works becaus I can run it and create it in offline mode, I.E. running it through console. The problem is that the variable I'm trying to write is populated through HTTP Post, and when I run the script through the browser, or when apache runs the script, it does not write or create the file. What do I need to do to allow access to write/change syntax wise to get this script to write this text file?
Your problem is likely due to apache not having permissions to write to the file location you specified. Go to that directory and check the permissions and group ownership with the ls command:
cd "My working file location"
ls -l .
There are three columns in the output that show the permissions, owner, and group for the directory. Most likely they are owned by root and don't have permissions for apache to write to the directory.
If this is the case, then you will see an error appear in your apache log when it tries to create the file. Try tailing your logs while running the script in your browser:
tail -f /var/log/apache2/error.log
I had the same trouble recently and stumbled upon this question. Unfortunately choppyfireballs the OP said in a comment he found his own solution and just accepted an answer that wasn't helping any of us... Then after a search and a success to make file_put_contents work again I decided to share my solution.
The permissions of my files and directories were ok to accept any writing (make sure your directories are chmod 757 this will give the root and others the grant to write files in the location). If it still doesn't work like it didn't for me, that's because your system is probably SELinux (Security Enhanced Linux) system.
If you want to make sure write setenforce 0 this will turn selinux to permissive mode, run your script again, if it works then it means the problem is well described.
In that case turn selinux on back setenforce 1 and try ls -Zl in the directory where the directory of your project is. this will give you a line like
drwx---r-x. 9 root root system_u:object_r:httpd_sys_content_t:s0 4096 Dec 8 00:25 project
or something different but httpd_sys_content_t if you used chcon to transfer the context from one directory to this one. but if you don't have httpd_sys_content_t it's ok because we need to change the context of that directory anyways.
first you need to accept any public_content_rw_t contexts to write file. Type
setsebool -P httpd_anon_write on
This will set (P)ermanently SELinux boolean httpd_anon_write to true and any context dubbed as public_content_rw_t will have the rights to write any files in their own location.
Now you have to say SELinux that your project directory is public_content_rw_t or you'll still not be able to write files. Type :
semanage fcontext --add --type public_content_rw_t "/project(/.*)?"
and restorecon -RvF /project to tell selinux to apply the above specifications.
Now your directory is public_content_rw_t and you should be able to write files.
I ran into this problem too. In my case, I found that the ownership of the directory was wrong. For a typical Apache installation the directory should be owned by www-data:www-data, not root:root.
Something else to try, for people with a similar question. You might just be making a simple mistake that doesn't require you to mess around with the file permissions—and if you're making this mistake, fixing the file permissions might not help.
Be sure you're using a local, relative file path in file_put_contents().
For example, use:
file_put_contents('short_local_path/my_working_file.txt', $myString);
Not:
file_put_contents('http://example.com/remote_path/my_working_file.txt', $myString);
And not:
file_put_contents('/whole/root/file/path/to/my_working_file.txt', $myString);
Have you tried chmodding the directory to 777?
Try this:
if(file_put_contents('file.txt', 'text')){
die('yes');
} else {
die('no');
}
Might of misspelled something. ^
Related
I'm trying to use PHP to create a file, but it isn't working. I am assuming this is because it doesn't have write access (it's always been the problem before). I tried to test if this was the problem by making the folder chmod 0777, but that just ended up making every script in that directory return a 500 error message until I changed it back.
How do I give PHP write access to my file system so it can a create a file?
Edit: It is hosted on Hostgator shared hosting using Apache.
Edit 2: Someone asked for the code:
The code is a GD image script. I know the rest of it works as previously I was creating the image every ime it was called. Now I am trying to create them when new text is added and save them to a folder. The write line I have is:
imagejpeg(null,$file,85);
I also created a test file to check if it was just a broken script (mainly copied from tizag):
http://gearboxshow.info/rkr/lesig.jpg/testfile.txt (I don't know if/how to post the code here properly. Here is the contents of the PHP script, minus PHP tags.)
It returns 13,13,1 (separate lines), so it looks as if it thinks it wrote something, but the testfile.txt is blank (I uploaded a blank one), or non-existent (if I delete it).
Edit 3: The server runs CentOS.
An easy way is to let PHP create the directory itself in the first place.
<?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 saves you the hassle with permissions.
Simple 3-Step Solution
Abstract: You need to set the owner of the directory to the user that PHP uses (web server user).
Step 1: Determine PHP User
Create a PHP file containing the following:
<?php echo `whoami`; ?>
Upload it to your web server. The output should be similar to the following:
www-data
Therefore, the PHP user is www-data.
Step 2: Determine Owner of Directory
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 be similar to the following:
drwxrwxr-x 2 exampleuser1 exampleuser2 4096 Mar 29 16:34 example-folder
Therefore, the owner of the directory is exampleuser1.
Step 3: Change Directory Owner to PHP User
Afterwards, 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 been changed:
ls -dl /var/www/example.com/public_html/example-folder
The result should be similar to the following:
drwxrwxr-x 2 www-data exampleuser2 4096 Mar 29 16:34 example-folder
Therefore, the owner of example-folder has successfully been changed to the PHP user: www-data.
Done! PHP should now be able to write to the directory.
Set the owner of the directory to the user running apache. Often nobody on linux
chown nobody:nobody <dirname>
This way your folder will not be world writable, but still writable for apache :)
1st Figure out which user is owning httpd process using the following command
ps aux | grep httpd
you will get a several line response like this:
phpuser 17121 0.0 0.2 414060 7928 ? SN 03:49 0:00 /usr/sbin/httpd
Here 1st column shows the user name. So now you know the user who is trying to write files, which is in this case phpuser
You can now go ahead and set the permission for directory where your php script is trying to write something:
sudo chown phpuser:phpuser PhpCanWriteHere
sudo chmod 755 PhpCanWriteHere
You can change the permissions of a folder with PHP's chmod(). More information on how to use the command is here: http://php.net/manual/en/function.chmod.php
If you get a 500 Error when setting the permissions to 777 (world writable), then it means your server is setup to prevent executing such files. This is done for security reasons. In that case, you will want to use 755 as the highest permissions on a file.
If there is an error_log file that is generated in the folder where you are executing the PHP document, you will want to view the last few entries. This will give you an idea where the script is failing.
For help with PHP file manipulation, I use http://www.tizag.com/phpT/filewrite.php as a resource.
I found out that with HostGator you have to set files to CMOD 644 and Folders to 755. Since I did this based on their tech support it works with HostGator
I had the same problem:
As I was reluctant to give 0777 to my php directory, I create a tmp directory with rights 0777, where I create the files I need to write to.
My php directory continue to be protected. If somebody hackes the tmp directory, the site continue to work as usual.
You can set selinux to permissive in order to analyze.
# setenforce 0
Selinux will log but permit acesses. So you can check the /var/log/audit/audit.log for details. Maybe you will need change selinux context. Fot this, you will use chcon command. If you need, show us your audit.log to more detailed answer.
Don't forget to enable selinux after you solved the problem. It better keep selinux enforced.
# setenforce 1
Best way in giving write access to a directory..
$dst = "path/to/directory";
mkdir($dst);
chown($dst, "ownername");
chgrp($dst, "groupname");
exec ("find ".$dst." -type d -exec chmod 0777 {} +");
chmod does not allow you to set ownership of a file. To set the ownership of the file you must use the chown command.
I'm running Ubuntu, and as said above nobody:nobody does not work on Ubuntu. You get the error:
chown: invalid group: 'nobody:nobody'
Instead you should use the 'nogroup', like:
chown nobody:nogroup <dirname>
Tiny little hint!
echo whoami;
make sure you use BACK QUOTES
NOT
single quotes ' '
!
(of course now the back quotes don't show up in this editor! oh well, I tried!)
I know this is a common issue but I haven't been able to single out the problem for my specific use case, so bear with me.
I have a simple PHP script send_id which simply sends an ID number and saves it to a TXT file on my RHEL server running Apache 2.4.6 with PHP 5.4.
The error message: Warning: file_put_contents(/var/www/html/id.txt): failed to open stream: Permission denied in /var/www/html/send_id.php on line 6
'1' written to server
The PHP script itself:
<?php
$id=$_GET['id'];
$stringData = "$id";
$file = file_put_contents('/var/www/html/id.txt', $stringData.PHP_EOL , FILE_APPEND |LOCK_EX);
echo "'$stringData' written to server";
?>
chmodding to 777 didn't do anything. Additionally, I checked to see ownership rights and noticed that the id.txt file is owned by the root user at both user/group level, and PHP is being run at root level.
Anyone have any suggestions? If its any help, this seems to have happened after a yum update
I resolved this issue by simply running chcon -Rt httpd_sys_content_rw_t on the directory where my troubled PHP script lived in.
The chcon command changes the SELinux context for files. However, changes made with the chcon command are not persistent across file-system relabels, or the execution of the restorecon command.
-Rt are to change the type of the directory and its contents, httpd_sys_content_rw_t is to give apache write access
source: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/sect-security-enhanced_linux-working_with_selinux-selinux_contexts_labeling_files
Additional note
ls -alZ *
The -Z switch will work with most utilities to show SELinux security contexts
Try changing the owner of the folder and the file to (chown) to "www-data" or to "www-data:www-data" and see if it changes anything...
Use a relative file path from, Apache's "DOCUMENT ROOT" to reference files in PHP. It's Apache's permissions that matter, and for security reasons it is coded to inhibit access to files outside of DOCUMENT_ROOT.. (yes even though your path leads within it, Apache is blocked as soon as it sees the path starts with "/VAR" ..
Assuming this PHP script is in the same directory as id.txt file , just use
$file = file_put_contents('./id.txt', $str...
Or if the txt file was in a sub-directory
file_put_contents('./sub-dir/id.txt', $str...
Not only is it secure, it's a lot shorter to type too.
This question has been asked many times, but none of the answers I found helped me.
I am trying to get php file_exists() to work. The only scenario when it works is when the php-file is in the same directory as the file to use file_exist() on and only using the file name (i.e. excluding the path). But it's not consequent behaviour, please see below.
Som information:
safe_mode=off
no symlinks for directory 28
no whitespace in the file name
All directories in /var/www/html/smic/upload/28/ has apache:apache 777 as permission.
Using php 5.3
PHP:
echo getcwd()
clearstatcache();
$file = 'file:///var/www/html/smic/upload/28/ul.txt';
//Also tried like this
//$file = '/var/www/html/smic/upload/28/ul.txt';
if(file_exists($file)){
echo $file." exists";
}
getcwd() prints /var/www/html/smic/modules/core/ticket
The permission of the php-script and the file to be checked is apache:apache 777.
Some details about the directory structure:
[root#localhost 28]# pwd
/var/www/html/smic/upload/28
[root#localhost 28]# ls -l ul.txt
-rw-r--r--. 1 apache apache 2 Feb 9 10:50 ul.txt
[root#localhost 28]# chmod 777 ul.txt
[root#localhost 28]# ls -l ul.txt
-rwxrwxrwx. 1 apache apache 2 Feb 9 10:50 ul.txt
The behaviour didn't change after changing the permission of the file. The directory /28 has drwxr-xr-x. for apache user and apache group
For test, I also moved the actual php-script to /28, gave it apache:apache 777 rigths. Changed the $file to "ul.txt" (i.e. $file = 'ul.txt';). That works, the ul.txt file is found.
getcwd() prints then /var/www/html/smic/upload/28
As another test I tried to find another file excluding the path in the "ticket" directory, the file wasn't recognized.
I'm banging my head...
Any advice is appreciated.
The permission of the file alone is not sufficient for php to assess file_exists. the process that runs php also needs permission to traverse all the parent directories of that file to get to it.
Check them one by one and verify that php can read and enter (r-x)
ls -ald /var
ls -ald /var/www
ls -ald /var/www/html
ls -ald /var/www/html/smic
ls -ald /var/www/html/smic/upload
ls -ald /var/www/html/smic/upload/28
Clutching at straws here...
Try su - apache (or whatever the user your webserver runs as.. apache2, www-data etc..) and then traversing the directory.
Are there any .htaccess files knocking about, or any other restrictions on your apache configuration?
Gee, this was a pretty tuff one. I always make sure when I copy anything from the web to first paste it into a normal texteditor in order to remove all strange/hidden characters, then copy the whatever again and paste it into my dev tool.
As I mentioned somewhere in a comment, I did pwd and copied the text form my virtual server to my osx. But what I didn't think about/know was that strange/hidden characters could follow if I did that from my linux server, hence I didn't make sure to copy everything via texteditor.
I remembered that I had problem quite some time ago when I copied from the web and figured this may be a similar kind of problem. I opened my script in an hex editor. And what did I find... '/var' looked lite this: '/var'. Removing the strange characters fixed the problem.
Thank you all for your comments above. Hope those can help someone else and perhaps it has helped me without even knowing it (since I did a lot of things based on your comments).
what's about the access rights to the folder?
the path $file = 'file:///var/www/html/smic/upload/28/ul.txt'; is incorrect.
Try the php script copy to folder upload and file='28/ul.txt';.
The folder must be readable.
Try to open the file using $file = '/upload/28/ul.txt';
From the php.net manual, "Upon failure, an E_WARNING is emitted." make sure error reporting is set to a level that will show warnings and try it.
Also, "This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.". You're not running in php safe mode are you? phpinfo() should tell you.
Where is your php file located? If within the "html" folder, then use a relative path like $file = "smic/upload/28/ul.txt";
Perhaps, in a name of the file there is a whitespace symbol. It's important.
I have just created a new folder on my server, and all the right permissions are set, I am sure of it.
The folder is there, but my PHP cant find the actual folder anyways?
Any ideas why?
The only thing I can think of is that my folder has special characters in its name.
I create it with this command:
sudo mkdir "Textiler & Sybehör"
I have lots of other directories with these kind of characters and they work fine.
Just this one seems to not work...
I am stuck!
PHP says cannot find directory...
UPDATE:
In command line tool, I tried moving the dir like this:
mv "Textiler & Sybehör" images/"Textiler & Sybehör"
I get this error:
cannot stat `Textiler & Sybeh\366r': No such file or directory
It is like if the letter "ö" isn't interpreted correctly.
When you make a directory with sudo that means it is created as the super or root user. If your web server is using suexec and running PHP as a normal user, PHP will not be able to access folders and/or files owned by other users.
Check to see if suexec is being used by or on your hosting provider or server.
The other thing is to determine if your folder really needs to be owned by the root user. If not, use the following command to change the owner: sudo chown <regular_user>:<regular_user> where <regular_user> is the account that PHP is running as.
Although it might be because of the characters in the name. What about folder structure? Do you have an .htaccess file with a rewrite base set? Code snippet would be great.
Also may as well check ownership permissions (chown) and then chmod the folder so it's writable.
I'm trying to use PHP to create a file, but it isn't working. I am assuming this is because it doesn't have write access (it's always been the problem before). I tried to test if this was the problem by making the folder chmod 0777, but that just ended up making every script in that directory return a 500 error message until I changed it back.
How do I give PHP write access to my file system so it can a create a file?
Edit: It is hosted on Hostgator shared hosting using Apache.
Edit 2: Someone asked for the code:
The code is a GD image script. I know the rest of it works as previously I was creating the image every ime it was called. Now I am trying to create them when new text is added and save them to a folder. The write line I have is:
imagejpeg(null,$file,85);
I also created a test file to check if it was just a broken script (mainly copied from tizag):
http://gearboxshow.info/rkr/lesig.jpg/testfile.txt (I don't know if/how to post the code here properly. Here is the contents of the PHP script, minus PHP tags.)
It returns 13,13,1 (separate lines), so it looks as if it thinks it wrote something, but the testfile.txt is blank (I uploaded a blank one), or non-existent (if I delete it).
Edit 3: The server runs CentOS.
An easy way is to let PHP create the directory itself in the first place.
<?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 saves you the hassle with permissions.
Simple 3-Step Solution
Abstract: You need to set the owner of the directory to the user that PHP uses (web server user).
Step 1: Determine PHP User
Create a PHP file containing the following:
<?php echo `whoami`; ?>
Upload it to your web server. The output should be similar to the following:
www-data
Therefore, the PHP user is www-data.
Step 2: Determine Owner of Directory
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 be similar to the following:
drwxrwxr-x 2 exampleuser1 exampleuser2 4096 Mar 29 16:34 example-folder
Therefore, the owner of the directory is exampleuser1.
Step 3: Change Directory Owner to PHP User
Afterwards, 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 been changed:
ls -dl /var/www/example.com/public_html/example-folder
The result should be similar to the following:
drwxrwxr-x 2 www-data exampleuser2 4096 Mar 29 16:34 example-folder
Therefore, the owner of example-folder has successfully been changed to the PHP user: www-data.
Done! PHP should now be able to write to the directory.
Set the owner of the directory to the user running apache. Often nobody on linux
chown nobody:nobody <dirname>
This way your folder will not be world writable, but still writable for apache :)
1st Figure out which user is owning httpd process using the following command
ps aux | grep httpd
you will get a several line response like this:
phpuser 17121 0.0 0.2 414060 7928 ? SN 03:49 0:00 /usr/sbin/httpd
Here 1st column shows the user name. So now you know the user who is trying to write files, which is in this case phpuser
You can now go ahead and set the permission for directory where your php script is trying to write something:
sudo chown phpuser:phpuser PhpCanWriteHere
sudo chmod 755 PhpCanWriteHere
You can change the permissions of a folder with PHP's chmod(). More information on how to use the command is here: http://php.net/manual/en/function.chmod.php
If you get a 500 Error when setting the permissions to 777 (world writable), then it means your server is setup to prevent executing such files. This is done for security reasons. In that case, you will want to use 755 as the highest permissions on a file.
If there is an error_log file that is generated in the folder where you are executing the PHP document, you will want to view the last few entries. This will give you an idea where the script is failing.
For help with PHP file manipulation, I use http://www.tizag.com/phpT/filewrite.php as a resource.
I found out that with HostGator you have to set files to CMOD 644 and Folders to 755. Since I did this based on their tech support it works with HostGator
I had the same problem:
As I was reluctant to give 0777 to my php directory, I create a tmp directory with rights 0777, where I create the files I need to write to.
My php directory continue to be protected. If somebody hackes the tmp directory, the site continue to work as usual.
You can set selinux to permissive in order to analyze.
# setenforce 0
Selinux will log but permit acesses. So you can check the /var/log/audit/audit.log for details. Maybe you will need change selinux context. Fot this, you will use chcon command. If you need, show us your audit.log to more detailed answer.
Don't forget to enable selinux after you solved the problem. It better keep selinux enforced.
# setenforce 1
Best way in giving write access to a directory..
$dst = "path/to/directory";
mkdir($dst);
chown($dst, "ownername");
chgrp($dst, "groupname");
exec ("find ".$dst." -type d -exec chmod 0777 {} +");
chmod does not allow you to set ownership of a file. To set the ownership of the file you must use the chown command.
I'm running Ubuntu, and as said above nobody:nobody does not work on Ubuntu. You get the error:
chown: invalid group: 'nobody:nobody'
Instead you should use the 'nogroup', like:
chown nobody:nogroup <dirname>
Tiny little hint!
echo whoami;
make sure you use BACK QUOTES
NOT
single quotes ' '
!
(of course now the back quotes don't show up in this editor! oh well, I tried!)