fopen() fails to create a file on linux

13,700

The PHP script is executed as the user configured for the Apache web server. In order to create files, this user has to have write permission to the directory in which you want to create the file. There are two ways to do this:

You can give the write permission to the directory for all users, which will include whatever is configured for Apache (good enough for a development machine):

chmod o+w ~/public_html/directory_where_you_want_to_write

Or you can pass the ownership of the directory to the Apache user. This will mean that you with your regular user account won't be able create or delete files in this directory though, unless you also do the above. Assuming Apache runs with the www-data user account, like it does by default on Ubuntu, you would do:

sudo chown www-data ~/public_html/directory_where_you_want_to_write

(And the directory doesn't have to be under public_html, I'm just using it as an example since that seems to be where your files are.)

Share:
13,700

Related videos on Youtube

Hamed Kamrava
Author by

Hamed Kamrava

DevOps enthusiast

Updated on June 04, 2022

Comments

  • Hamed Kamrava
    Hamed Kamrava almost 2 years

    I'm trying to create a file through fopen() as below :

    <?php 
      $handle = fopen('name.txt', 'w') or die('Can\'t create file');
      fwrite($handle, 'Hamed'."\n");
      fwrite($handle, 'Kamrava'."\n");
      echo 'File was created successfully';
    ?>
    

    But doesn't create that file and get me:

    Can't create file

    P.S :

    I'm using LAMP server on Linux/Ubuntu.

    I've tried below command before creating that file:

    sudo chmod -R 755 ~/public_html/
    

    Any ideas would be appreciated.

    • Alex Shesterov
      Alex Shesterov almost 11 years
      are you sure that ~/public_html/ is current working directory? Have you tried an absolute filename?
  • glglgl
    glglgl almost 11 years
    You can put your user into the appropriate group (www?) and then grant write access to the group.
  • a_horse_with_no_name
    a_horse_with_no_name over 9 years
    What is a ur tring?