File permissions for fopen in write mode - PHP

AlxVallejo picture AlxVallejo · Aug 15, 2012 · Viewed 15.2k times · Source

I have a PHP script that writes some rows to a CSV file:

$fp = fopen($csv, 'w');

I'm using mode 'w' so that it will create the file if it doesn't exist, however the file is automatically given 644 permissions even though I gave 777 to the whole /var/www/html/ directory (not a good idea but suitable for testing).

How can I write to the file and give it permissions beforehand? Or is there a better way to give write permissions?

Answer

Mike Mackintosh picture Mike Mackintosh · Aug 15, 2012

To create the file before hand and set permissions:

touch('/file/path/here');
chmod('/file/path/here', 0775);
fopen('/file/path/here', 'w');

But, this should not be an issue. If the PHP/Apache user is creating the file using fopen, they have permissions to write to it.