Uploading Files and Navigating Directories in PHP - Uploading files (
Page 2 of 4 )
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:
move_uploaded_file($_FILES['userfile']['tmp_name'],
'/upload/to/path/'. $filename);
To demonstrate, create a normal HTML form, and make the changes we've discussed to turn it into a upload form. Below is a example:
<html>
<head>
<title>Administration - upload new files</title>
</head>
<body>
<p>Upload File</p>
<form enctype="multipart/form-data" action="upload.php"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
Upload this file: <input name="userfile" type="file"><br>
<input type="submit" value="Upload File">
</form>
</body>
</html>
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.
Here's a screen shot of both scripts in action:

Fig2. A file is selected for uploading...

Fig3. File upload message...