Home » Php » file – php file_put_contents function not working

file – php file_put_contents function not working

Posted by: admin April 23, 2020 Leave a comment


Why would file_put_contents refuse to work for the following code?

$f = file_put_contents("files/r.js", "Some text here");

if ($f) print 1;
else print 0;
How to&Answers:

It could be a permission problem

Is the directory /files chmoded to 777? sometimes php won’t allow you to access directories if they don’t have enough permission. I don’t know about blank errors though.

Try to see if it has enough permissions, if not, then set it to 777 and try it.


Are you using the full path on the filesystem or are you trying to use the URI? I think this PHP function expects you to give the path as the file is found on the filesystem.

Relative paths should be okay though.

You may need to make sure the file exists and that it’s permissions are set to 777. Sometimes I’ve found that it’s not enough to just have the directory permissions set to 777 but the file must also already exist.


We’ve experienced this, requiring a workaround (regardless of method, permissions and anything else mentioned here). When all other fixes failed, we have found it can be linked to restrictions created by SELinux.


It is because of SELINUX.

You can mark the folder as of type httpd_sys_rw_content_t with this command to enable writing to this folder.

semanage fcontext -a -t httpd_sys_rw_content_t '/files(/.*)?'; restorecon -RF '/files/'


If you’re using windows the following solution worked perfectly for me on Windows 10 running php 5.5.38

If you’re having this problem on Windows/IIS try the following:

  1. Go to the Folder that you are trying to write to and right click it, then select properties.
  2. Select the Security Tab
  3. Click Edit
  4. Click Add
  5. Click Advanced
  6. Click Find Now
  7. From the list of User select IUSR and click OK
  8. Click OK again.
  9. The IUSR will be displayed in the top box labelled ‘Group of User Names’
  10. Select IUSR and grant necessary permissions in the ‘Permissions for BATCH’ list view.
  11. Click Apply and then you are done.

The steps may be slightly different for different versions of windows. This also applies to ASP.NET though I think the users you add are the network users (NETWORK AND OR NETWORK SERVICE users) as well as the IUSR.