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

October 2017




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.
Published by jak58. Latest update on October 18, 2012 at 06:05 AM by jak58.
This document, titled "PHP - Control the size/format of an image before upload," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).