HomePHP Page 2 - Uploading Files and Navigating Directories in PHP
Uploading files - PHP
In this article we are going to look at how to upload files and also how to navigate through directories. It is the second part of a tutorial that began last week with "Reading, Writing, and Creating Files in PHP."
When a file is uploaded, it is first placed in a temporary directory. You have to use the move_uploaded_file() function to move it to its final destination. The move_uploaded_file function takes three parameters:
Now let's create a script to handle the uploaded file:
Script: do_upload.php <? //define the upload path $uploadpath = "c:uploads"; //check if a file is uploaded if($_FILES['userfile']['name']) { $filename = trim(addslashes($_FILES['userfile']['name'])); //move the file to final destination if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadpath."/". $filename)) { echo "The file has been uploaded"; } else{ if ($_FILES['userfile']['error'] > 0) { switch ($_FILES['userfile']['error']) { case 1: echo 'File exceeded upload_max_filesize'; break; case 2: echo 'File exceeded max_file_size'; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break; } exit; } } } ?>
The do_upload script first sets the upload path by declaring
'$uploadpath = "c:uploads";
This is where our files are going to be stored on our C drive. Next we check to see whether the Files array is filled:
' if($_FILES['userfile']['name']) {'
If it is filled, the 'move_upload_file()' function is used to upload the file and a message is shown. In case the array is not filled we define a switch statement with the various error numbers and what they mean:
case 1: echo 'File exceeded upload_max_filesize'; break; case 2: echo 'File exceeded max_file_size'; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break;
One of these errors will be executed when an error number is found in the File array.