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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With