PHP and MySQL Upload with Resize Image

Advertisement

If you’re searching on a short, direct and simple PHP and MySQL upload and re-size script, well you’re in the right place folks, today I’ll share you how easily this scripts is and I’m using this script too in my web projects and it works fine, one of the CMS that uses this method is WordPress of course there’s a lot more 😉

Why we have to re-size image?

The answer is pretty simple, although there are lots that are need to consider but the most common are, first server load and space second web speed (remember Google love faster website) and more, hey it’s an optional so if you have SSD and lighting speed server then you don’t need to re-size images 🙂

Okay lets go, are you ready?

HTML Code

This contains HTML form code for upload.


<!--please do not tear or rip enctype, this is the most important form parameters in uploading files-->
<form enctype="multipart/form-data" method="post">
	<fieldset>
		<p><label for="file">Filename:</label><br/>
			<input type="file" name="file" />
		</p>
		<p>
			<input type="hidden" name="task" value="upload" />
			<input type="submit" value="Upload File" />
		</p>
	</fieldset>
</form>

PHP Code

These script simply re-size image into two, 50px and 100px and before saving into database it added time stamp into the image(s) name, this to avoid conflict in other previous uploaded images.

I’ll add comment as long as I can so no need to tear the code apart and explain line by line, hope this work for you guys.


<?php
//include our config db
include ('config.php');

$error = '';
$success = '';

if( isset( $_POST['task']) && 'upload' == $_POST['task'] )
{
	// get uploaded file name
	$image = $_FILES["file"]["name"];

	if( empty( $image ) ) {
		$error = 'File is empty, please select image to upload.';
	} else if($_FILES["file"]["type"] == "application/msword") {
		$error = 'Invalid image type, use (e.g. png, jpg, gif).';
	} else if( $_FILES["file"]["error"] > 0 ) {
		$error = 'Oops sorry, seems there is an error uploading your image, please try again later.';
	} else {

		// strip file slashes in uploaded file, although it will not happen but just in case ;)
		$filename = stripslashes( $_FILES['file']['name'] );
		$ext = get_file_extension( $filename );
		$ext = strtolower( $ext );

		if(( $ext != "jpg" ) && ( $ext != "jpeg" ) && ( $ext != "png" ) && ( $ext != "gif" ) ) {
			$error = 'Unknown Image extension.';
			return false;
		} else {
			// get uploaded file size
			$size = filesize( $_FILES['file']['tmp_name'] );

			// get php ini settings for max uploaded file size
			$max_upload = ini_get( 'upload_max_filesize' );

			// check if we're able to upload lessthan the max size
			if( $size > $max_upload )
				$error = 'You have exceeded the upload file size.';

			// check uploaded file extension if it is jpg or jpeg, otherwise png and if not then it goes to gif image conversion
			$uploaded_file = $_FILES['file']['tmp_name'];
			if( $ext == "jpg" || $ext == "jpeg" )
				$source = imagecreatefromjpeg( $uploaded_file );
			else if( $ext == "png" )
				$source = imagecreatefrompng( $uploaded_file );
			else
				$source = imagecreatefromgif( $uploaded_file );

			// getimagesize() function simply get the size of an image
			list( $width, $height) = get_image_size( $uploaded_file );
			$ratio = $height / $width;

			// new width 50(this is in pixel format)
			$nw = 50;
			$nh = ceil( $ratio * $nw );
			$dst = imagecreatetruecolor( $nw, $nh );

			// new width 100 in pixel format too
			$nw1 = 100;
			$nh1 = ceil( $ratio * $nw1 );
			$dst1 = imagecreatetruecolor( $nw1, $nh1 );

			imagecopyresampled( $dst, $source, 0, 0, 0,0, $nw, $nh, $width, $height );
			imagecopyresampled( $dst1, $source, 0, 0, 0, 0, $nw1, $nh1, $width, $height );

			// rename our upload image file name, this to avoid conflict in previous upload images
			// to easily get our uploaded images name we added image size to the suffix
			$rnd_name = 'photos_'.uniqid(mt_rand(10, 15)).'_'.time().'_50x50.'.$ext;
			$rnd_name1 = 'photos_'.uniqid(mt_rand(10, 15)).'_'.time().'_100x100.'.$ext;

			// move it to uploads dir with full quality
			imagejpeg( $dst, '/uploads/'.$rnd_name, 100 );
			imagejpeg( $dst1, '/uploads/'.$rnd_name1, 100 );

			// I think that's it we're good to clear our created images
			imagedestroy( $source );
			imagedestroy( $dst );
			imagedestroy( $dst1 );

			// so all clear, lets save our image to database
			$is_uploaded = mysql_query( "INSERT INTO attachment(photosmall, photobig) VALUES('$rnd_name', '$rnd_name1')" ) or die('erroror inserting data '. mysql_erroror());

			// check if it uploaded successfully, if so then display success message otherwise the erroror message in the else statement
			if( $is_uploaded )
				$success = 'Post shared successfully.';
			else
				$error = 'erroror uploading file.';

		}

	}
}
?>

PHP Function

A very simple PHP function to get and return the file extension.


function get_file_extension( $file )  {
	if( empty( $file ) )
		return;

	// if goes here then good so all clear and good to go
	$ext = end(explode( ".", $file ));

	// return file extension
	return $ext;
}

Final Words: How and when this snippet is useful? this code is very useful to less your server load, and to lighten your site display by using re-sized images, Google love faster website so of course SEO 😉

Happy coding ^_^

Advertisement