ZaZaKi, a web developer Between Manchester UK & Rotterdam NL. © 2015-2024.

php image upload

Image upload with thumbnail and orginal size

<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(!empty($_FILES['image']['name'])){
$thumb_width = '100'; 
$thumb_height = '100';
$original_width = '600'; 
$file_name = 'my_image'; 
$file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION); 
$fileName = $file_name.'.'.$file_ext; 

//upload image path
$upload_image = 'uploads/'.basename($fileName);

//upload image
if(move_uploaded_file($_FILES['image']['tmp_name'],$upload_image)){
		$thumbnail = 'uploads/thumbs/'.$fileName;
		$original = 'uploads/original/'.$fileName;		
		list($width,$height) = getimagesize($upload_image);		
		
		// 10 is 10% of 100.
		$percent = $height / $width;
		$percent = number_format( $percent * 100 ); 
		$original_height = ($percent / 100) * $original_width;
		
		$thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
		$original_create = imagecreatetruecolor($original_width,$original_height);		
		switch($file_ext){
			case 'jpg':
				$source = imagecreatefromjpeg($upload_image);
				break;
			case 'jpeg':
				$source = imagecreatefromjpeg($upload_image);
				break;

			case 'png':
				$source = imagecreatefrompng($upload_image);
				break;
			case 'gif':
				$source = imagecreatefromgif($upload_image);
				break;
			default:
				$source = imagecreatefromjpeg($upload_image);
		}

		imagecopyresized($thumb_create,$source,0,0,0,0,$thumb_width,$thumb_height,$width,$height);		
		imagecopyresized($original_create,$source,0,0,0,0,$original_width,$original_height,$width,$height);		
		switch($file_ext){
			case 'jpg' || 'jpeg':
				imagejpeg($thumb_create,$thumbnail,100);
				imagejpeg($original_create,$original,100);
				break;
			case 'png':
				imagepng($thumb_create,$thumbnail,100);
				imagepng($original_create,$original,100);
				break;

			case 'gif':
				imagegif($thumb_create,$thumbnail,100);
				imagegif($original_create,$original,100);
				break;
			default:
				imagejpeg($thumb_create,$thumbnail,100);
				imagejpeg($original_create,$original,100);
		}
}else{
	return false;
}
 
   unlink($upload_image);
   echo "<script>location.reload(); return false;</script>";
   
   
}else{

 echo "<p>Select an image please!</p>";
}

}

?>

<form id="myform" method="post" enctype="multipart/form-data" >
<p>Select an Image: <br><input type="file" name="image"/></p>
<p><input type="submit" name="submit" value="Upload the image"/></p>
</form>

<p><img src="uploads/thumbs/my_image.jpg"></p>
<p><img src="uploads/original/my_image.jpg"></p>
<script>
if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}
</script>
Categroy:
back-end , PHP