A few words of thanks would be greatly appreciated.

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


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.

A few words of thanks would be greatly appreciated.

Ask a question
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

Published by . Latest update on 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 (https://ccm.net/).