PHP - Control the size/format of an image before upload

October 2016


I want to control the size and format of an image before upload (display and error message if necessary). How to do this in PHP?


You can try to adapt the below code to your convenience:

if((isset($_FILES['file'])) && ($_FILES['file']['name']!="")) {  
echo 'isset'.$_FILES['file']['name'];  
$folder = 'upload/';  
$file = basename($_FILES['file']['name']);  
$size_maxi = 2000000;  
$size = filesize($_FILES['file']['tmp_name']);  
$extensions = array('.png', '.gif', '.jpg', '.jpeg', '.pdf', '.doc', '.docx', '.xls', '.xlsx');  
$extension = strrchr($_FILES['file']['name'], '.');  
//Start the file type verification 
//If the extension is not in table 
if(!in_array($extension, $extensions)){  
$error = 'You must make use of file in the following forma type png, gif, jpg, jpeg, txt ..etc...';  
$error = 'File size is above allowed limitations...';  
//If no error detected, proceed to upload 
//format file name here 
echo 'non error';  
$file = strtr($file,  
$file = preg_replace('/([^.a-z0-9]+)/i', '-', $file);  
//If function returns TRUE, then it worked 
if(move_uploaded_file($_FILES['file']['tmp_name'], $folder . $file)) {  
echo "Upload successful"  
//If the function returns FALSE. 
echo 'Upload fail'.$error;  


Thanks to asmaanoor for this tip.

Related :

This document entitled « PHP - Control the size/format of an image before upload » from CCM ( is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.