Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fopen() fails to create a file on linux

Tags:

linux

php

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.

like image 719
Hamed Kamrava Avatar asked Jul 21 '13 19:07

Hamed Kamrava


1 Answers

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.)

like image 145
Joni Avatar answered Oct 21 '22 16:10

Joni