A simple PHP file upload tutorial
This PHP file upload tutorial is concentrated on mainly for beginners. Generally we face many problems in file uploading. Like checking fie extensions on client and server side, processing file as our requirement.
For this we need two files called uploader.html and uploader.php
In uploader.html we do form validation and checking file extensions.
In uploader.php we do check for user submitted file extensions.
Some observations<
- Always-set form method to POST
- Always-set form encodedtype to multipart/form-data
- Check file type on client side and server side also.
- Increase the script time limit and memory limit to upload large file.
- Don’t use web method (this method) to upload larger than 500mb,instead use ftp upload interface.
Generally the default maximum upload file size less than 8mb.
To upload the larger or bigger files read increase file upload limit
Add a simple Form to page as shown below
<form id="uploadform" action="uploader.php" enctype="multipart/form-data" method="post"> <label>Upload File <input id="filefield" name="filefield" type="file" /> </label> <label> <input id="Upload" name="Upload" type="submit" value="Upload" /> <!-- This hidden input will force the PHP max upload size. it may work on all servers. --> <input name="MAX_FILE_SIZE" type="hidden" value="100000" /> </label> </form> |
Add validation script to page as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <script type="text/javascript"> function validatefile(){ var myform=document.uploadform; //reference to form var file_field_value=myform.filefield.value; //access form value with dom model var error=""; if(file_field_value==''){ error+="Please Select A file.n"; } var allowed_extensions=/(jpg|jpeg|bmp|giff|doc|docx|pdf)$/; //check for allowed extension it is simple regular expression if(!file_field_value.match(allowed_extensions)){ error+="Please select only jpeg or jpg or bmp or giff or doc or pdf ."; } if(error!=''){ //check for any errors alert(error); //if error alert error return false; //return to form don't submit to action page } return true; // every thing going fine return true allow form to submit the data. } </script> |
Check file status and process the page on server side.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php if (isset($_POST['Upload'])) { //check if form submitted if (!empty($_FILES['filefield'])) { //check for image submitted if ($_FILES['filefield']['error'] > 0) { // check for error re file echo "Error: " . $_FILES["filefield"]["error"] . "<br />"; } else { print_r($_FILES); //every thing fine file successfully uploaded to server } } else { die('File not uploaded.'); // exit script } } ?> |
now a simple validation and uploading the file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | if (!isset($_POST)){die('You can"t access this file directly');}//avoid direct accessing to this file. if (isset($_POST['Upload'])) { //check if form submitted if (!empty($_FILES['filefield'])) { //check for image submitted if ($_FILES['filefield']['error'] > 0) { // check for error re file echo "Error: " . $_FILES["filefield"]["error"] . "<br />"; } else { $file=$_FILES['filefield']; //every thing fine. file successfully uploaded to server } } else { die('File not uploaded.'); // exit script } } $upload_directory='uploaded/'; $ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf"; $allowed_extensions=explode(',',$ext_str); $max_file_size = 10485760;//10 mb remember 1024bytes =1kbytes $overwrite_file = false; /* upload directory check */ $status = true; if (!is_dir($upload_directory)) { //check if upload directory exists or not if ($mkdir) { if (!mkdir($upload_directory)) { //if directory doesn't exists try to create it,if fails warn user $status = false; } else { if (!chmod($upload_directory, 0777)) $status = false; //change file permisson to write,read,execute } } else { $status = false; } } if(!$status){ //if can't make a directory warn the user and exit die('There is no uploade directory or i can" create the upload directory'); } /* check allowed extensions here */ $ext = substr($file['name'], strrpos($file['name'], '.') + 1); //get file extension from last sub string from last . character if (!in_array($ext, $allowed_extensions) ) { die('only'.$ext_str.' files allowed to upload'); // exit the script by warning /* check file size of the file if it exceeds the specified size warn user */ if($file['size']>=$max_file_size){ die('only the file less than '.$max_file_size.'mb allowed to upload'); // exit the script by warning } /* check if the file already exists or not in the upload directory */ if(!$overwrite_file and file_exists($upload_directory.$file['name']) ){ die('the file '.$file['name'].' already exists.'); // exit the script by warning } if(!move_uploaded_file($file['tmp_name'],$upload_directory.$file['name'])){ die('The file can"t moved to target directory..'); //file can't moved with unknown reasons likr cleaning of server temperory files cleaning } /* Hurrey we uploaded a file to server successfully. */ |

