PHP image upload file size and file type validation
We validate the PHP image upload file size and already uploading the check. move_uploaded_file() function is used to upload the file by accessing file data stored in $_FILES superglobal in-build PHP variable.
I am using this PHP that I got from here, and it works. Example of PHP image upload file size and file type validation. with an HTML form to allow users to upload images Size of image extension.
Note : any time you can upload file form tag in enctype=”multipart/form-data” added.
index.php
<html>
<br /><br />
<body style="text-align: center;">
<h2>PHP image upload file size and file type validation</h2>
<form action="process.php" metod="post" enctype="multipart/form-data">
Images ( JPG, PNG, GIF, JPEG ): <br /><br />
<input type="file" name="images" /><br /><br />
<input type="submit" value="UPLOAD">
</form>
</body>
</html>
process.php
<?php
$messages = array();
$image_file = $_FILES['images']['name'];
if(empty($_FILES['images']['name']))
{
$messages[]= "Please select file.";
}
if(!(strtoupper(substr($_FILES['images']['name'],-4))==".JPG"
|| strtoupper(substr($_FILES['images']['name'],-5))==".JPEG"
|| strtoupper(substr($_FILES['images']['name'],-4))==".GIF"
|| strtoupper(substr($_FILES['images']['name'],-4))==".PNG")) {
$messages[]="Upload file type is wrong! only allow .jpg,.jpeg,.png,gif.";
}
if(file_exists("uploads/".$_FILES['images']['name']))
{
$messages[]="Uploaded file already exists.";
}
/* file size validation ex: Maximum 30 KB then 2048*15 */
if($_FILES['images']['size'] > (15*2048) ) {
$messages[]="Upload file size more then 30KB";
}
if(!empty($messages)) {
echo '<ul>';
foreach($messages as $er)
{
echo '<li>'.$er.'</li>';
}
echo '</ul>';
} else {
if (move_uploaded_file($_FILES["images"]["tmp_name"], $image_file)) {
echo "The ". $_FILES["images"]["name"]. " has successfully uploaded.";
} else {
echo "Sorry, Something we are wrong!";
}
}
?>