PHP Sets Incorrect Permissions With move_uploaded_file()

Date Initially Written: 10 July 2009.

Problem: When running a PHP script that uses the move_uploaded_file() function the permissions are set incorrectly on the copied file.

Operating System: Windows XP Professional with service pack 3, PHP 5.2.6.

Background: A website I was working on allowed the user to upload photos. As part of the upload process I used the move_uploaded_file() function to copy the uploaded file from the temporary directory to a directory within the website. When I went to look at the uploaded files I found the permissions were not as I expected them (i.e. the permissions hadn't been inherited from the parent directory).

Resolution Steps: When uploading files through a form PHP will store them in a temporary directory while the script is running. It is the script's responsibility to copy the file elsewhere if it needs to be kept, otherwise PHP will automatically delete the uploaded file when the script ends. Exactly which directory is used to store the temp files is specified within the php.ini file (see the upload_tmp_dir directive).

I discovered that the temporary directory has to have the same permissions on it as I wanted to be set on the copied file. For example if there is a user called Murray and I wanted that user to have access to the uploaded file then it wasn't enough to just give Murray access to the directory that the uploaded file will be copied to, I also had to give Murray access to the temporary directory that PHP uses to store the uploaded file.

I believe this behaviour occurs because PHP moves the file rather than copies and deletes it. For more information about this see Microsoft Knowledge Base Article 310316.

Recommended Reading For PHP Programmers: Programming PHP