Search This Blog

PHP File Upload Script


Uploading a file using PHP to a web server is a basic function. But many students having difficulty in understanding this process. So, I created this simple script to explain you how to upload a file to web server using PHP and HTML Form.

First we need to create an HTML form with a special additional option in the form tag. When uploading a file we need to define the "enctype" stands for encode type. This tell the browser how to send data to the web server. We need to use "multipart/form-data" as the enctype when uploading files.




You need to include this form in an HTML file with proper headers and definitions. After selecting a file (in this case a photo) and when click on the submit button, web browser sends file data to the web server. Following PHP script validate and save file in the web server.


// ********************* global image upload script ***************************//
if($_FILES['photo']['name'] == '') { // if this is empty, no file is selected, show error message
$error = "Please select an image file to upload";
}else{
$attachment = strtolower($_FILES['photo']['name']); // convert file name to lower case
$attachment = str_replace(" ", "_", $attachment); // replace white spaces with underscore
        // photo should be either jpg or peng and less than 5MB
if ((
($_FILES['photo']['type'] == "image/png") || 
($_FILES['photo']['type'] == "image/jpeg") || 
($_FILES['photo']['type'] == "image/pjpeg")
) && ($_FILES['photo']['size'] < 5000000)) {
if ($_FILES['photo']['error'] > 0) { // if server error occurs
// There is an error in the uploaded file
$error = 'There was an error in the uploaded file. Please upload again!';
}else{
// No errors in the uploaded file, proceed to uploading the file
$attachment = rand(111,999)."_".$attachment; // create a random file name
$save_file = "files/".$attachment; // save file in "files" folder
move_uploaded_file($_FILES['photo']['tmp_name'], $save_file); // save file
}
}else{
$error = "Error during the file upload, please try again!";
}
}
// *********************** end of photo upload script ********************************//
?>

You can create a function  using this script and easily call the function when need to upload a file.

No comments:

CheqMate - චෙක් ලියන මෘදුකාංගය

The best cheque writing software in Sri Lanka. Your investment is only Rs.9,500/- for the lifetime. We give a CD to reinstall the softw...