move_uploaded_file gives "failed to open stream: Permission denied" error
Solution 1:
This is because images
and tmp_file_upload
are only writable by root
user. For upload to work we need to make the owner of those folders same as httpd process owner OR make them globally writable (bad practice).
- Check apache process owner:
$ps aux | grep httpd
. The first column will be the owner typically it will benobody
-
Change the owner of
images
andtmp_file_upload
to be becomenobody
or whatever the owner you found in step 1.$sudo chown nobody /var/www/html/mysite/images/ $sudo chown nobody /var/www/html/mysite/tmp_file_upload/
-
Chmod
images
andtmp_file_upload
now to be writable by the owner, if needed [Seems you already have this in place]. Mentioned in @Dmitry Teplyakov answer.$ sudo chmod -R 0755 /var/www/html/mysite/images/ $ sudo chmod -R 0755 /var/www/html/mysite/tmp_file_upload/
For more details why this behavior happend, check the manual http://php.net/manual/en/ini.core.php#ini.upload-tmp-dir , note that it also talking about
open_basedir
directive.
Solution 2:
You can also run this script to find out the Apache process owner:
<?php echo exec('whoami'); ?>
And then change the owner of the destination directory to what you've got. Use the command:
chown user destination_dir
And then use the command
chmod 755 destination_dir
to change the destination directory permission.
Solution 3:
This worked for me.
sudo adduser <username> www-data
sudo chown -R www-data:www-data /var/www
sudo chmod -R g+rwX /var/www
Then logout or reboot.
If SELinux
complains, try the following
sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www(/.*)?'
sudo restorecon -Rv '/var/www(/.*)?'
Solution 4:
If you have Mac OS X, go to the file root or the folder of your website.
Then right-hand click on it, go to get information, go to the very bottom (Sharing & Permissions), open that, change all read-only to read and write. Make sure to open padlock, go to setting icon, and choose Apply to the enclosed items...
Solution 5:
I wanted to add this to the previous suggestions. If you are using a version of Linux that has SELinux enabled then you should also execute this in a shell:
chcon -R --type httpd_sys_rw_content_t /path/to/your/directory
Along with giving your web server user permissions either through group or changing of the owner of the directory.