Apache not allowing PHP to create file

I am trying to save data using HTML and PHP in localhost in Ubuntu. My HTML & PHP files are working great but when I am using commands to open a file in the localhost using

$myfile = fopen("testfile.txt", "w")

it does not allow it to create it, but the PHP file is working and when set with commands to output variables from PHP it works well.

How to permit PHP to create files in Apache in localhost Ubuntu.


Solution 1:

You must allow the Apache user (usually www-data) to create files in that directory. This can be accomplished by making Apache the owner of the directory, for example, if the directory were called my-dir, you would open a terminal and run this:

sudo chown www-data my-dir

Solution 2:

as stated on the Apache2 Ubuntu Default Page: By default, Ubuntu does not allow access through the web browser to any file apart of those located in /var/www .... This means that any directory or file you want to write to must be under /var/www. Missed this info myself and got my hair pulling for a while trying to write to /tmp etc.

Solution 3:

If you want to change all the folders and files within that directory, and not just the directory, add -R like so

sudo chown -R www-data my-dir