PHP image upload implementation code with detailed comments

  • 2020-03-31 20:42:42
  • OfStack

 
<?php 
//User uploads image processing file
if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/pjpeg"))&& ($_FILES["file"]["size"] < 100000)){ //Controls the type of image allowed to be uploaded, and the final 100,000 is the allowed image size
if ($_FILES["file"]["error"] > 0){ 
echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; //Returns the error
}else{ 
/* //This is the information of the uploaded picture, remove the before and after comments to see the effect.
echo "Upload: " . $_FILES["file"]["name"] . "<br />"; 
echo "Type: " . $_FILES["file"]["type"] . "<br />"; 
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; 
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; */ 
if (file_exists("userupload/" . $_FILES["file"]["name"])){ 
echo $_FILES["file"]["name"] . " already exists. "; 
}else{ 
move_uploaded_file($_FILES["file"]["tmp_name"],"userupload/" . $_FILES["file"]["name"]); 
} 

$date=date('Ymdhis'); //Get the current time, such as; 20070705163148
$fileName=$_FILES['file']['name']; //Get the name of the uploaded file
$name=explode('.',$fileName); //Split the filename with '.' to get the suffix, and you get an array
$newPath=$date.'.'.$name[1]; //Get a new file as '20070705163148.jpg', that is the new path
$oldPath=$_FILES['file']['tmp_name']; //Temporary folder, the previous path
rename("userupload/".$fileName,"userupload/".$newPath); 

//Here you can write your SQL statement. The address of the image is "userupload/".$newPath

?> 
<script type="text/javascript">alert(' Picture uploaded successfully !!');</script> 
<?php 
} 
}else{ 
echo "Invalid file"; //Wrong image type or too large
} 
?> 

Related articles: