Uploading files with PHP
How do I upload a file with PHP?
Uploading a file or even multiple files in PHP is extremely easy. The first thing you need is a simple HTML form, like so:
The script that handles this form, upload.php, then looks like this:
// Is the file there
if (isset($_FILES['file']) == false OR $_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
die('No files');
}
// No problems?
if ($_FILES['file']['error'] != UPLOAD_ERR_OK) {
die('Error occured during upload');
}
// Move file to our upload folder
$path = '/home/phpit/uploads/';
$newfile = $path . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $newfile);
die('Your file has been successfully uploaded.');
?>
The above code first checks to make sure a file has been uploaded, and displays an error if it hasn't. After that a simple check is done to make sure everything else went okay, using the inbuilt file uploading error constants (see the PHP manual for more information).
The uploaded is then moved to the upload directory, which is an important step, because the uploaded file cannot stay in the temporary directory (where it gets placed initially by PHP). If you do leave the file in the temp directory, there's a big chance that it will be removed, when the temp directory gets cleared automatically.
You can also upload multiple files at the same time, by using multiple form elements, i.e.
The PHP code that handles this form is very similar to the single-upload code, e.g.
echo 'File 1: ' . $_FILES['file1']['name'] . '';
echo 'File 2: ' . $_FILES['file2']['name'] . '';
echo 'File 2: ' . $_FILES['file2']['name'] . '';
?>
That's all there is to know about uploading files in PHP. If you want to read about more in-depth about this, have a look at the PHP manual.
August 2nd, 2006 at 8:29 am
erm…actually i wanna ask about uploading multiple files but juz using one input inbox..like after we have success upload a file..then to upload another one file using the already input inbox..then display the file that we hv upload i the same page as the file we have upload before this..
August 4th, 2006 at 11:26 pm
I’m disapointed with this explanation. You’re not using PHP to upload a file at all. You’re using the same old HTML form which does the upload to a temporary file, and then using PHP to simply copy that file from the temporary directory to it’s final destination.
The problem with this is that HTML upload has severe size limitations and doesn’t solve the needs of uploading larger files which is more relevant today.
August 8th, 2006 at 5:21 am
to eric..
y dont u response to my question..can u tell me how to upload using the php..to upload the files..refering to my question..
August 8th, 2006 at 10:40 am
eric…
plz help me..i relly need a help,,,
August 30th, 2006 at 5:47 pm
hi pls give the steps to upload a file using php ..