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

Ask a question



Issue


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?

Solution


You can try to adapt the below code to your convenience:
<?php  

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...';  
}  
if($size>$size_maxi){  
$error = 'File size is above allowed limitations...';  
}  
//If no error detected, proceed to upload 
if(!isset($error)){  
//format file name here 
echo 'non error';  
$file = strtr($file,  
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',  
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');  
$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. 
else{  
echo 'Upload fail'.$error;  
}  
}  
}  

?> 


Thanks to asmaanoor for this tip.
Jean-François Pillou

CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Learn more about the CCM team