Handling file uploads POST method uploads This feature lets people upload both text and binary files. With PHP's authentication and file manipulation functions, you have full control over who is allowed to upload and what is to be done with the file once it has been uploaded. PHP is capable of receiving file uploads from any RFC-1867 compliant browser. Related Configurations Note See also the file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size and max_input_time directives in &php.ini; PHP also supports PUT-method file uploads as used by Netscape Composer and W3C's Amaya clients. See the PUT Method Support for more details. File Upload Form A file upload screen can be built by creating a special form which looks something like this:
Send this file:
]]>
The __URL__ in the above example should be replaced, and point to a PHP file. The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work. The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name. $_FILES['userfile']['name'] The original name of the file on the client machine. $_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted. $_FILES['userfile']['size'] The size, in bytes, of the uploaded file. $_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server. $_FILES['userfile']['error'] The error code associated with this file upload. Files will, by default be stored in the server's default temporary directory, unless another location has been given with the upload_tmp_dir directive in &php.ini;. The server's default directory can be changed by setting the environment variable TMPDIR in the environment in which PHP runs. Setting it using putenv from within a PHP script will not work. This environment variable can also be used to make sure that other operations are working on uploaded files, as well. Validating file uploads See also the function entries for is_uploaded_file and move_uploaded_file for further information. The following example will process the file upload that came from a form. '; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Possible file upload attack!\n"; } echo 'Here is some more debugging info:'; print_r($_FILES); print ""; ?> ]]> The PHP script which receives the uploaded file should implement whatever logic is necessary for determining what should be done with the uploaded file. You can, for example, use the $_FILES['userfile']['size'] variable to throw away any files that are either too small or too big. You could use the $_FILES['userfile']['type'] variable to throw away any files that didn't match a certain type criteria, but use this only as first of a series of checks, because this value is completely under the control of the client and not checked on the PHP side. Also, you could use $_FILES['userfile']['error'] and plan your logic according to the error codes. Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere. If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none. The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed. Uploading array of files PHP supports HTML array feature even with files.

Pictures:

]]>
$error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; // basename() may prevent filesystem traversal attacks; // further validation/sanitation of the filename may be appropriate $name = basename($_FILES["pictures"]["name"][$key]); move_uploaded_file($tmp_name, "data/$name"); } } ?> ]]>
File upload progress bar can be implemented using Session Upload Progress.
Error Messages Explained PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error']. UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success. UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in &php.ini;. UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form. UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded. UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded. UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo may help. Common Pitfalls The MAX_FILE_SIZE item cannot specify a file size greater than the file size that has been set in the upload_max_filesize in the &php.ini; file. The default is 2 megabytes. If a memory limit is enabled, a larger memory_limit may be needed. Make sure you set memory_limit large enough. If max_execution_time is set too small, script execution may be exceeded by the value. Make sure you set max_execution_time large enough. max_execution_time only affects the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system, the sleep function, database queries, time taken by the file upload process, etc. is not included when determining the maximum time that the script has been running. max_input_time sets the maximum time, in seconds, the script is allowed to receive input; this includes file uploads. For large or multiple files, or users on slower connections, the default of 60 seconds may be exceeded. If post_max_size is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough. The max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items. Not validating which file you operate on may mean that users can access sensitive information in other directories. Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature. Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly. A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]). Uploading multiple files Multiple files can be uploaded using different name for input. It is also possible to upload multiple files simultaneously and have the information organized automatically in arrays for you. To do so, you need to use the same array submission syntax in the HTML form as you do with multiple selects and checkboxes: Uploading multiple files Send these files:


]]>
When the above form is submitted, the arrays $_FILES['userfile'], $_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be initialized. For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth. $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set. The max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit.
PUT method support PHP provides support for the HTTP PUT method used by some clients to store files on a server. PUT requests are much simpler than a file upload using POST requests and they look something like this: This would normally mean that the remote client would like to save the content that follows as: /path/filename.html in your web tree. It is obviously not a good idea for Apache or PHP to automatically let everybody overwrite any files in your web tree. So, to handle such a request you have to first tell your web server that you want a certain PHP script to handle the request. In Apache you do this with the Script directive. It can be placed almost anywhere in your Apache configuration file. A common place is inside a <Directory> block or perhaps inside a <VirtualHost> block. A line like this would do the trick: This tells Apache to send all PUT requests for URIs that match the context in which you put this line to the put.php script. This assumes, of course, that you have PHP enabled for the .php extension and PHP is active. The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have. With PHP you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy. Saving HTTP PUT files ]]> &reftitle.seealso; Filesystem Security