How to validate image size and type in PHP?

This post is for developers who want to know how to validate image size and type in PHP. This article will show you the basics of what we need to do and how we can use functions like getimagesize() to get image dimensions in PHP and strtolower().

It’s important that your images are the right size, otherwise, they may not load properly or be used as intended. You’ll also want them to be formatted correctly so they don’t appear blurry on different devices. We’ll go over both of these things in this blog post! If you’re looking for just one way to validate images, then this is it! Read on below to find out more about our favorite method.

CONTENTS

Basic image upload script

First, you need to create a simple image upload form in HTML. Here is the basic structure with Bootstrap 4. You can use your own style as per your need.

<!doctype html>
<html lang="en">
	<head>
		<!-- Required meta tags -->
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

		<!-- Bootstrap CSS -->
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

		<title>PHP Image Upload with Size and Type Validation</title>
	</head>
	<body>
		<div class="container mt-5">
			<div class="row d-flex align-items-center justify-content-center">
				<div class="col-md-8">
					<fieldset class="border p-4">
						<legend  class="float-none w-auto p-2">PHP Image Upload with Size and Type Validation</legend>
						<form action="index.php" method="post" enctype="multipart/form-data">
							<div class="form-group">
								<abel for="logo">Choose Image file:</label>
								<input type="file" class="form-control-file" id="logo" name="logo">
							</div>
							<button type="submit" name="upload" class="btn btn-success mb-2 float-right">Upload</button>
						</form>
					</fieldset>
				</div>
			</div>
		</div>
		<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  </body>
</html>

Here is the basic image upload script without any validation in PHP:

<?php
	if (isset($_POST["upload"])) {
		
		$location = "image/" . basename($_FILES["logo"]["name"]);
		
        if( move_uploaded_file($_FILES["logo"]["tmp_name"], $location)) {
            
			echo "Image uploaded successfully.";
        }
		
	}
?>

How to use different types of PHP image upload validation functions?

So, the above example is a basic one. Now we are going to validate the image size and type. We will look at each validation process step by step and create the final code by merging all the validation processes at the end.

How to validate file input to check if is not empty?

We must first check that the file input is not blank. To do that follow the code below.

<?php
    if ( file_exists($_FILES["logo"]["tmp_name"]) ) {
         
         //if input is not blank, do upload part

    }

By using file_exists() function, we are going to check if the temporary file exists.

How to validate image extension in PHP?

To avoid an error when uploading a file with an incorrect extension, you need to validate the image type first. We can easily check it by using pathinfo() function like this:

<?php
        //store allowed extension
        $allowed_ext = array(
			"jpg",
			"jpeg",
			"png",
			"gif"
		);
		
		//get file extension
		$file_ext = strtolower( pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION) );
		
		if ( in_array($file_ext, $allowed_ext)) {
			
			//do upload part
			echo $file_ext;

		}else{
			
			//wrong image type
			
		}

In the above example, we have defined an array i.e. $allowed_ext which will store all allowed extensions. Now using pathinfo() and PATHINFO_EXTENSION we are going to get the extension of the uploaded file.

Here we are using strtolower() function to convert the extension into lowercase. This is because if the uploaded file extension is in uppercase it will not going to match in in_array() function.

How to validate image type in PHP?

It is not possible to understand the file type just by checking the extension. If someone renames a .php file extension to.jpg, it is not possible to validate it with the above code. So in this validation process, we are going to check image types.

<?php
        //list of all allowed image types
        $allowed_types = array(
			"image/gif",
			"image/jpeg",
			"image/pjpeg",
			"image/jpeg", 
			"image/pjpeg",
			"image/png",
			"image/x-png"
		);
		
		//get file type
		$file_type = mime_content_type($_FILES['logo']['tmp_name']);

		if ( in_array($file_type, $allowed_types)) {
			
			//do upload part
			
		}else{
			
			//wrong image type
			
		}

In the above example, I have set different types of allowed MIME types of an image. The mime_content_type() function returns the MIME content type of the uploaded image.

If you change any non-image file extension to .jpg, the above script will detect the original file type, and depending on the allowed file types it will work as per the condition.

How to validate Image size in PHP?

We see a lot of times, there are some restrictions in the case of image upload, for example, the image must be within 2MB or the image size must be within 150kb. But how to do this. Well, check the code below.

<?php
		$file_size = $_FILES["logo"]["size"];
		
		//image size should be in 150kb
		if ($file_size <= 150000) {
			
			//do upload part
			
		}else{
			
			//wrong image type
			
		}

In the above example, I have set the maximum file size will be 150kb. Now convert 150kb to byte. The result will be 150000 bytes. If you also want the image size below 2MB, you have to write 2000000.

How to validate Image dimension in PHP?

Suppose, you want the dimensions of the image to be between 800×600. So, you can use the below code to check if the image dimension is valid or not.

<?php
	if (isset($_POST["upload"])) {
		
		$image_file = @getimagesize($_FILES["logo"]["tmp_name"]);
		$width = $image_file[0];
		$height = $image_file[1];
		
		if ($width <= "800" || $height <= "600") {
			
			//do upload part
			
		}else{
			
			//wrong image type
			
		}

The getimagesize() function will return the dimensions of any image. If you noticed, I have used the “@” symbol in front of that function. It means, it will suppress the error message thrown by that function.

Now get the width and height from the $image_file array and check if the file dimensions are within 800×600.

How to show the image validation message?

Now we have all kinds of validation processes. Now we will see how to show validation message in case of each validation.

Here we will create an array object called $status with two keys i.e. type and message.

$status = array(
	"type" => "alert-danger",
	"message" => "Image size should be within 150kb."
);


$status = array(
	"type" => "alert-success",
	"message" => "Image successfully uploaded."
);

Here I have written alert-danger and alert-success as the value of type. As we are using Bootstrap 4, it will help to show the alert box. Let’s display the error message.

<?php if(!empty($status)) { ?>
<div class="alert text-center <?php echo $status['type'];?>" role="alert">
<?php echo $status['message'];?>
</div>
<?php } ?>

How to show post_max_size error message?

Each server has a specific file upload limit. It is often observed that if the size of an image file exceeds the file upload limit in php.ini, then no error message is shown. So, users have difficulty understanding where is the real problem?

Here we will check if there is an upload limit issue by using the below code.

<?php
if(
	isset( $_SERVER['REQUEST_METHOD'] )      &&
	($_SERVER['REQUEST_METHOD'] === 'POST' ) &&
	isset( $_SERVER['CONTENT_LENGTH'] )      &&
	( empty( $_POST ) )
){
	$max_post_size = ini_get('post_max_size');
	$content_length = $_SERVER['CONTENT_LENGTH'] / 1024 / 1024;
	if ($content_length > $max_post_size ) {
		$status = array(
			"type" => "alert-danger",
			"message" => sprintf(
				'It appears you tried to upload %d MiB of data but the PHP post_max_size is %d MiB.',
				$content_length,
				$max_post_size
			) .
			'Try increasing the post_max_size setting in your php.ini file.'
		);
		
	}
}

The above code will check if $_SERVER['REQUEST_METHOD'] is POST and also check content_length has been set i.e. $_SERVER['CONTENT_LENGTH']. At last, check if $_POST is empty.

Now merge all functions to make a working image validation script. Here is the full code below.

<?php

	//check if method is POST
	if($_POST) {
		
		//check if file input is not empty
		if ( isset($_FILES["logo"]) && file_exists($_FILES["logo"]["tmp_name"]) ) {
			
		
			//list of all allowed extension
			$allowed_ext = array(
				"jpg",
				"jpeg",
				"png",
				"gif"
			);
			
			//get file extension
			$file_ext = strtolower( pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION) );
			
			
			
			//list of all allowed file types
			$allowed_types = array(
				"image/gif",
				"image/jpeg",
				"image/pjpeg",
				"image/jpeg", 
				"image/pjpeg",
				"image/png",
				"image/x-png"
			);
			
			//get file type
			$file_type = mime_content_type($_FILES['logo']['tmp_name']);
			
			
			
			
			//get image file size
			$image_file = @getimagesize($_FILES["logo"]["tmp_name"]);
			$width = $image_file[0];
			$height = $image_file[1];
			
			
			//get file size
			$file_size = $_FILES["logo"]["size"];
			
			
			//image extension an file type
			if( !in_array($file_ext, $allowed_ext) || !in_array($file_type, $allowed_types) ){
				
				$status = array(
					"type" => "alert-danger",
					"message" => "Not a valid image. Only PNG, JPEG and GIF are allowed."
				);
				
				
			}
			//check image size
			elseif( $file_size > 150000 ){
				
				$status = array(
					"type" => "alert-danger",
					"message" => "Image size should be within 150kb."
				);
				
			}
			//check image dimensions
			else if( $width > "800" || $height > "600") {
				
				$status = array(
					"type" => "alert-danger",
					"message" => "Image dimensions should be within 800X600."
				);
				
			}
			//if all ok lets upload image
			else{
				$location = "image/" . basename($_FILES["logo"]["name"]);
				
				
				if( move_uploaded_file($_FILES["logo"]["tmp_name"], $location)) {
					
					$status = array(
						"type" => "alert-success",
						"message" => "Image successfully uploaded."
					);
					
				}else{
					
					$status = array(
						"type" => "alert-danger",
						"message" => "Something went wrong."
					);
				}
				
				
			}
			
			
		}else{
			
			$status = array(
				"type" => "alert-danger",
				"message" => "Select an image."
			);
			
		}//check end of empty image
		
		
	}//end of post
	
	if(
		isset( $_SERVER['REQUEST_METHOD'] )      &&
		($_SERVER['REQUEST_METHOD'] === 'POST' ) &&
		isset( $_SERVER['CONTENT_LENGTH'] )      &&
		( empty( $_POST ) )
	){
		$max_post_size = ini_get('post_max_size');
		$content_length = $_SERVER['CONTENT_LENGTH'] / 1024 / 1024;
		if ($content_length > $max_post_size ) {
			$status = array(
				"type" => "alert-danger",
				"message" => sprintf(
					'It appears you tried to upload %d MiB of data but the PHP post_max_size is %d MiB.',
					$content_length,
					$max_post_size
				) .
				'Try increasing the post_max_size setting in your php.ini file.'
			);
			
		}
	}
?>

<!doctype html>
<html lang="en">
	<head>
		<!-- Required meta tags -->
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

		<!-- Bootstrap CSS -->
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

		<title>PHP Image Upload with Size and Type Validation</title>
	</head>
	<body>
		<div class="container mt-5">
			<div class="row d-flex align-items-center justify-content-center">
				<div class="col-md-8">
					
					<fieldset class="border p-4">
						<legend  class="float-none w-auto p-2">PHP Image Upload with Size and Type Validation</legend>
						
						<?php if(!empty($status)) { ?>
						<div class="alert text-center <?php echo $status['type'];?>" role="alert">
							<?php echo $status['message'];?>
						</div>
						<?php } ?>
						
						<form action="index.php" method="post" enctype="multipart/form-data">
							<div class="form-group">
								<abel for="logo">Choose Image file:</label>
								<input type="file" class="form-control-file" id="logo" name="logo">
							</div>
							<button type="submit" name="upload" class="btn btn-success mb-2 float-right">Upload</button>
						</form>
					</fieldset>
				</div>
			</div>
		</div>
		<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  </body>
</html>

How to check image width and height before upload in PHP?

PHP Server Side Language. So after submitting the form the image is uploaded to the server as a temporary file. Once uploaded, the file is stored in a specific location after completing various validations.

So it is not possible to get the size of that image file in any way with PHP without uploading it to the server. After submitting the form you need to wait until the file is uploaded to the server as a temporary file and then you can get the size like below.

<?php
   $image_file = @getimagesize($_FILES["logo"]["tmp_name"]);
   $width = $image_file[0];
   $height = $image_file[1];

But it can be possible to check the image width and height before uploading using jQuery.

How to validate image height, width before upload using jQuery?

You can check image height and width before uploading using jQuery. Let’s check the code.

$(document).ready(function(){
	
	var _URL = window.URL || window.webkitURL;
	
	$('#logo').change(function () {
		var file = $(this)[0].files[0];

		img = new Image();
		var imgwidth = 0;
		var imgheight = 0;
		var maxwidth = 800;
		var maxheight = 600;

		img.src = _URL.createObjectURL(file);
		img.onload = function() {
			imgwidth = this.width;
			imgheight = this.height;
			
			if(imgwidth <= maxwidth && imgheight <= maxheight){

				$( '<div class="alert text-center alert-danger" role="alert">Image dimensions should be within 800X600</div>' ).insertAfter( "legend" );
				$('#logo').val(null);
			}
			
		}
		
		
	});
});

In the above example, you can check after selecting the image we are creating an image object and also set the image maximum height and width. Now on onload event, get the image height and width.

After that, check the height and width with maximum height and width. If the size is exceeded show an error message and also clear the file input.

Conclusion

We hope this article has been helpful in your understanding of how to validate image sizes and types. If you have any questions or would like more information about our expertise, please don’t hesitate to reach out to us by commenting below for any assistance!

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment