I have a PHP script where I can upload a file and it will try to move it from /tmp to test/ (relative path which is in my project folder, for example /var/www/html/myproject/test would be the absolute path). When this happens I get the following error.
move_uploaded_file(test/test.csv): failed to open stream: Permission denied in /var/www/html/myproject/import.php on line X, referer: http://192.168.1.1/myproject/import2.php
This script is run by the apache user who has ownership of /test (both apache owner and apache group own this directory) with rwx permissions.
Here's what I have checked:
- safe_mode is disabled.
- open_basedir is not set.
- file_uploads are turned on.
- upload_max_filesize is 2MB, file is ~50KB.
- post_max_size is 8MB, my post request is not close to this.
- Used absolute path instead of relative path.
- is_dir("test/") returns true.
- is_writable("test/") returns false.
- from within the php script: printed file owner (for file I'm trying to move), folder owner (test/), file permissions, and folder permissions. file / folder owner shows apache. File permissions are 600 so owner can read and write. Folder permissions are 755, so owner can read, write, and execute.
- ps -aux | grep apache. Matched the PID in the apache error log to the process that is running which is owned by the apache user. So, this confirms the process is running under apache.
- getcwd() and
__DIR__
both return the correct directory /var/www/html/myproject. - dirname(
__FILE__
) returns the correct absolute path to the file - Checked file_exists($_FILES['file']['tmp_name']) returns true
- Checked $_FILES['file']['error'] (the file I'm trying to move) returns 0, no issues uploading.
- Checked the source folder (/tmp) with is_writable("/tmp") which is true.
- Tried chmod -R 777 on test/ temporarily, still says permission denied and is not writable.
- Disabled antivirus / edr temporarily
- Checked security context of "test/". Returns this: "unconfined_u:object_r:httpd_sys_content_t:s0". None of these are an issue (explanations in my reply below).
- Checked for security related apps which might prevent moving a file. These are not installed: AppArmor, grsecurity, Tomoyo Linux, and Smack.
- Used fopen() / flock() function in php script to confirm that the file I'm trying to move isn't locked.
- Used is_uploaded_file() function to confirm that I'm trying to move an uploaded file (losing my mind at this point and just trying anything I can think of). This of course returns true.
move_uploaded_file requires two parameters. 1: the file you want to upload 2: the absolute path of to put the file into 3: please ensure that the upload directory has the proper ownership and permissions (note: directory ownership should belong to user:group of apache2 if you're using Apache as a proxy).
Read more: https://www.php.net/manual/pt_BR/function.move-uploaded-file.php