CIAS Secure PHP File Upload Example
Send this file:
Source code
CIAS Secure PHP File Upload Example
Send this file:
#This is an array which you can manage to determine which file types you want to allow to upload $allowedFileTypes = array("jpg","png","bmp","gif","pdf"); #This is where you want to upload, this directory much be writable by the webserver (777 on cias.rit.edu) $uploaddir = 'sample_upload_directory/'; #This is a statement that will kill your script if your upload directory doesn't exist and isn't writeable by the webserver if(!is_dir($uploaddir) && !is_writable($uploaddir)) { echo "Your upload directory has not been created or setup properly!!"; die(); } #We define and rename the file here, I've simply tacked on a timestamp, but you can get creative if you want $uploadfile = $uploaddir . time()."_".basename($_FILES['userfile']['name']); #We now get some information about the file, so we can check its extension $uploadfileinfo = pathinfo($_FILES['userfile']['name']); #In this line we are making sure that our upload script is being run from... our upload script, #You can replace $_SERVER['SCRIPT_URI'] with the name of the URL you expect your script to be run from. (ie a sperate upload.html file) if($_SERVER['SCRIPT_URI'] == $_SERVER['HTTP_REFERER']) { #Lets make sure our POST variable exists and that the form has been submitted if(isset($_POST)) { #This checks if our uploaded file has an extension that we set up in the $allowedFileTypes array above if(in_array($uploadfileinfo['extension'],$allowedFileTypes) ) { #Ok, this statement actually moves the uploaded from the tmp directory to our final destination if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { chmod($uploadfile, 0644); #Ok, everything has been uploaded just fine, this is where you would update your MySQL database, #or any other manipulation you need to do echo "File is valid, and was successfully uploaded."; echo "View file:
here
"; print_r($uploadfileinfo); } else { #This else statement really just means, something happened in your upload and you got an error echo "Possible file upload attack!\n"; } } else { #This is where you would handle your 'not allowed' extentions. echo "The file: ". $uploadfileinfo['basename'] ." is not an allowed file type"; } } }