<p>How can you allow a PHP script to write to a file with high-security restrictions, such as only allowing a single user to write to it?</p>

<p>The difficulty seems to be that a PHP script is running as a low-permissions user (maybe apache, or www, or nobody?), and even if I <code>chown</code> apache the_writable_file, the directory it's in might not be writable for the low-level user.  In general, what's the usual way that PHP can work with local files in a secure way?</p>

[{'answer_id': 34018, 'author': 'hoyhoy', 'author_id': 3499, 'author_profile': 'https://Stackoverflow.com/users/3499', 'pm_score': 0, 'selected': False, 'text': '<p>Sure, <code>chgrp apache the_writable_file</code> and <code>chmod g+w the_writable_file</code>.  After that, only your secure user and the apache user will be able to write to the file.  Since the apache user is typically forbidden from logging in, you only have to worry about web users writing to your secure file using through the http daemon.</p>\n'}, {'answer_id': 34054, 'author': 'John Douthat', 'author_id': 2774, 'author_profile': 'https://Stackoverflow.com/users/2774', 'pm_score': 3, 'selected': True, 'text': '<p>Unfortunately, in shared hosts that use <strong>mod_php, there is no way to restrict access</strong> to secure files to your web app and login user.</p>\n\n<p>The solution is to <strong>run your web app as your login user</strong>. When you do that, UNIX file permissions can correctly lock everyone else out. There are several ways to implement that, including <a href="http://httpd.apache.org/docs/2.0/suexec.html" rel="nofollow noreferrer">SuExec</a>, <a href="http://www.suphp.org/Home.html" rel="nofollow noreferrer">suPHP</a>, or running PHP with FastCGI with <a href="http://fastcgi.coremail.cn/" rel="nofollow noreferrer">mod_fcgid</a> or <a href="http://mproxyfcgi.sourceforge.net/" rel="nofollow noreferrer">mod_proxy_fcgid</a>. FastCGI is my favorite way.</p>\n\n<p>Another solution is to use a dedicated host or virtual private server.</p>\n'}, {'answer_id': 34058, 'author': 'Jiaaro', 'author_id': 2908, 'author_profile': 'https://Stackoverflow.com/users/2908', 'pm_score': 0, 'selected': False, 'text': '<p>All the containing folders need to have execute permissions.</p>\n\n<p>For example, if the file\'s in <code>/foo/bar/the_writable_file</code>, the directories "foo" and "bar" both need to have executable permission to access the_writable_file, even if they don\'t have read/write permission.</p>\n'}]
['https://Stackoverflow.com/questions/34015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3561/']