On File Permissions in Linux
In Linux web server process is used to run as different user as used for logging in and uploading/storing files. You need to check what user your web server is running as. After that you need to check if that user is permitted to write files into selected target folder.
Using this command on server will show user name installed web server is running as (requiring privileged access):
$ sudo ps aux | awk '$11 ~ /apache|lighttpd|nginx|cherokee/ {print $1}' | grep -v root | uniq
After that you might check if target folder is writable by that user (mostly, it's www-data
).
:
$ sudo -u www-data /bin/touch -- /path/to/your/file
If this prints "Permission denied" you need to fix permissions on containing folders. This implies the selected target folder and all its parents for the latter might prevent web server from even reading subfolders web server is actually permitted to write into. See this example:
-
/var
is world-readable and world-executable (or world-enterable on folders).
-
/var/www
is world-readbale and world-enterable.
-
/var/www/private
is owner-enterable only and not owned by your web server.
-
/var/www/private/target
is your target folder made web server writable before.
In this scenario web server won't be permitted to write in /var/www/private/target
for it's not even permitted to enter that one's parent folder /var/www/private
.
But don't use chmod 0777 /pathname
just because it's the easiest to do!
Basically I'm used to have my existing folders owned by my login user, but group set to group of web server. If you have folders web server is designed to store files in, you could simply grant write privilege to group on that single folder.
$ chown myuser:www-data /var/www
$ find /var/www -type d | xargs chmod 0750
$ find /var/www '!' -type d | xargs chmod 0640
$ chmod g+w /var/www/upload
Note:
- In first command,
www-data
isn't name of a user, but name of a group. It's usually same as web server's user name, but it might differ in your case.
-
/var/www
is used as example here and should point to your application's root folder. Subfolder upload
is yet another example for subfolder web server might write files into.
How to select target folders in PHP
According to your code the target folder is given relatively. In that case you won't find the folder all this checking has to be done in for you don't know what folder your target folder is actually related to. You might try binding your relative target folder's name to the folder your PHP script resides in using some code like this:
$path = dirname( __FILE__ ) . '/event-image/';
or
$path = dirname( __FILE__ ) . '/../upload/event-image/';
It depends on your application's folder layout. But this way you are using some absolute pathname for moving file and it's still working in different contexts or on different servers.