Upload, Resize, write to mySQL and get thumbnail from multiple images

While ago i found this post and made some changes. I edit it so multiplie fields can be posted to PHP and all images can be saved to mySQL database.
Function is uploading images and at same time re sizing them. Function creates small thumbnail pictures and saves image to the database.

You will need mySQL database so paths of images can be stored.

create table 'slike_ap'
(
'id' INT NOT NULL primary key AUTO_INCREMENT,
'user_id' int,
'ap_id' int,
'small'varchar,
'big' varchar,
);

PHP script

This script uploads and resizes images. Take a look at $newwidth if you have to modify size values. Ad more variables in array $slike for more pictures

<?php
error_reporting(0);

$change="";
$abc="";

 define ("MAX_SIZE","400");
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 $errors=0;

	$connection = mysql_connect("localhost","root","");
	if (!$connection) {
		die("Database connection failed: " . mysql_error());
	}

	$db_select = mysql_select_db("test",$connection);
	if (!$db_select) {
		die("Database selection failed: " . mysql_error());
	}

	$slike = array(file, file1, file2, file3, file4);
  if($_SERVER["REQUEST_METHOD"] == "POST")
 {

	$filearray = array();
	$filearray1 = array();
	$k=0;

  foreach($slike as $slika){
	$image =$_FILES[$slika]["name"];
	$uploadedfile = $_FILES[$slika]['tmp_name'];
 	if ($image)
 	{

 		$filename = stripslashes($_FILES[$slika]['name']);

  		$extension = getExtension($filename);
 		$extension = strtolower($extension);

 if (($extension != "jpg") && ($extension != "jpeg") &&
				($extension != "png") && ($extension != "gif"))
 		{

 			$change='<div class="msgdiv">Unknown Image extension </div> ';
 			$errors=1;
 		}
 		else
 		{

 $size=filesize($_FILES[$slika]['tmp_name']);

if ($size > MAX_SIZE*1024)
{
	$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
	$errors=1;
}

if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES[$slika]['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}
else if($extension=="png")
{
$uploadedfile = $_FILES[$slika]['tmp_name'];
$src = imagecreatefrompng($uploadedfile);

}
else
{
$src = imagecreatefromgif($uploadedfile);
}

echo $scr;

list($width,$height)=getimagesize($uploadedfile);

$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=130;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);

$image_name=(time()+$k).'.'.$extension;

$filename = "images/". $image_name;

$filename1 = "images/small_". $image_name;

imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

$filearray[$k]= $filename;
$filearray1[$k]= $filename1;
$k++;

	mysql_query("Insert into slike_ap set user_id='2',
	ap_id='2',big='$filename',small='$filename1' ", $connection);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
}
if(isset($_POST['Submit']) && !$errors)
 {
  	$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
 }
?>

 

You can download a whole script with html, highslide JS and comments. Try it your self and leave a comment if something stucks!

 

You may also like...

32 Responses

  1. 9Lessons is one of the best sites that I saw in our area. I saw a lot of influences of their, in here. And I hope that your blog become so good as the 9Lessons.
    Congrats for the Tut…

  2. Wonderful line up. We’ll be linking to this wonderful post on our internet site. Sustain the nice composing.

  3. Greg says:

    Could you tell me a way after my image is resized i can put it on top of another image?

    • Munge says:

      I don’t understand the question, can you be specific?

      • Greg says:

        I figured it out already, but I changed the form so I could insert info into the dtatbase along with the pictures but it doesnt want to insert my other fields do you know how I can do this?

        • Munge says:

          check for the database, did you created other fields in database you are trying to insert

          • Greg says:

            yes the other fields are there. Say I want to upload 5 pictures and for each picture there is a name and description field. I fill in that info for all five pictures and click submit, it adds all 5 pics to the database but as for the other info it only adds what was posted for image 5. Its like it missing an array or something for the other info

          • Munge says:

            For each name and description you haw to create a new array inside for each loop in my script like for the behind $filearray = array();
            $filearray1 = array(); just add
            $image_name = array();
            $description = array ();

            did you do that ?

          • Greg says:

            I tried this and it post to the database put it inserts the word array instead of the values I put in

          • Munge says:

            can you upload somewhere your work and i’l try to fix it for you ?

          • Greg says:

            here is what I got so far. I got it to insert rows 2-5 but doesnt want to insert row 1

          • Munge says:

            i think this is how you do it

      • Greg says:

        Still don’t work, but I don’t see where you changed anything. Looks like the same file I sent you

        • Munge says:

          ouuu sorry I uploaded wrong file
          here is right

          • Greg says:

            Still not working right. Adds the image name to database still but nothing else.

          • Munge says:

            sorry for loong edit, i updated my file i’t was esier for me to work on that , you just need to implement that on your sript , for mee this is working
            http://www.box.com/s/4dee3vz6a1xkleax8tr3

          • Greg says:

            You are awesome works good. Got one other question, is there a way to make it if I dont have a image I can upload the other information and do the image later. Right now if i enter a name type and description but no image it will not insert any data but if I insert image and type it will insert them both and leave description empty

          • Munge says:

            I’t wuld need a different concept to whole thing, first you need to modifie the check for enteries , haw to use logic operator or , file or desc or type, so you can insert in mySQL fealds with onley data you entered,
            For update those fields you will haw to first call them whith sql comands and use them as default in form, its a bite complicated, I wuld rather create a new page for update where you can call all entries from database.
            This is great script for editing entries http://www.9lessons.info/2011/04/live-table-edit-delete-with-pagination.html

  4. Greg says:

    Thanks for the help. Ill check out the 9 lessons tut. Could you delete the links I posted please

  5. Westman says:

    Hi,
    I added 2 more variables in array slike but then it don’t want to upload all pictures if all of them are filled with files. What’s wrong?

  6. kamal says:

    I want to upload images from a URL. (from another sever)
    what are the changes i have to do…

    thank you!

  7. Westman says:

    It’s a wonderful script and after hard use I noticed something: If your second or third picture is bigger than MAX_SIZE the the previous one/s are uploaded and recorded in db and than the error msg comes. So I end up with error msg and uploaded pictures. Can this be hadled someway.

    • Westman says:

      I found some way to hadle this situation. I just put some rollback script at the end of this. Just if some errors are found the whole data is deleted.

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha Captcha Reload