Jump to content

Photo upload, thumbnail, and database scripts


ericburnard

Recommended Posts

Hey again!!

 

I have a piece of code i found on a forum that will upload and make a thumbnail of the uploaded image. I have changed a few pieces and tried adding some parts to make it take extra fields from the form and put them into a database. The code i have is below

 


<?php

$upload_image_limit = 2; // How many images you want to upload at once?
$upload_dir = "./images/uploads/main/"; // default script location, use relative or absolute path
$thumb_dir = "./images/uploads/main/"; // default script location, use relative or absolute path
$enable_thumbnails = 1 ; // set 0 to disable thumbnail creation
$max_image_size = 3024000 ; // max image size in bytes, default 1MB

##################### THUMBNAIL CREATER FROM GIF / JPG / PNG

function make_thumbnails($updir, $img){

$thumbnail_width = 80;
$thumbnail_height = 60;
$thumb_preword = "thumb_";

$arr_image_details = GetImageSize("$updir"."$img");
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];

if( $original_width > $original_height ){
$new_width = $thumbnail_width;
$new_height = intval($original_height*$new_width/$original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width*$new_height/$original_height);
}

$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);



if($arr_image_details[2]==1) { $imgt = "ImageGIF"; $imgcreatefrom = "ImageCreateFromGIF"; }
if($arr_image_details[2]==2) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; }
if($arr_image_details[2]==3) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; }


if( $imgt ) {
$old_image = $imgcreatefrom("$updir"."$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imageCopyResized($new_image,$old_image,$dest_x,
$dest_y,0,0,$new_width,$new_height,$original_width,$original_height);
$imgt($new_image,"$updir"."$thumb_preword"."$img");
}

}

################################# UPLOAD IMAGES

foreach($_FILES as $k => $v){

$img_type = "";
$caption= "cap".$i."" ;
### $htmo .= "$k => $v<hr />"; ### print_r($_FILES);

if( !$_FILES[$k]['error'] && preg_match("#^image/#i", $_FILES[$k]['type']) && $_FILES[$k]['size'] < $max_image_size ){

$img_type = ($_FILES[$k]['type'] == "image/jpeg") ? ".jpg" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/gif") ? ".gif" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/png") ? ".png" : $img_type ;

$img_rname = $_FILES[$k]['name'];
$img_path = $upload_dir.$img_rname;

copy( $_FILES[$k]['tmp_name'], $img_path );
if($enable_thumbnails) make_thumbnails($thumb_dir, $img_rname);
$feedback .= "Image and thumbnail created $img_rname with caption $caption<br />";

include ('db.php');
$con = mysql_connect("$host","$username","$password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }mysql_select_db("erikee10_eric", $con);

$sql="INSERT INTO photos (address, cap)
VALUES
('$img_rname', '$caption')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }


}
}

############################### HTML FORM
while($i++ < $upload_image_limit){
$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br /> <input type="text" name="cap'.$i.'" value="cap'.$i.'">';
}

$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';

echo $htmo;
echo "$s";
?>

 

 

I have tried different was from POST script to putting in another loop to increase the cap number when it goes to insert the data. I spent 4 hours on it last night trying different ways and im stumped now. Any help would be great!

 

Thanks a million

 

Eric

Your form code is producing a series of fields with name="uplimg1", name="uplimg2", name="uplimg3", ... To iterate over those, you would need to reference $_FILES["uplimg1"], $_FILES["uplimg2"], $_FILES["uplimg3"], ... That's not what your code is doing.

 

I recommend that you use array names for your form fields, then you can simply use a foreach(){} loop to iterate over all the corresponding form fields. See example #3 at the following link - http://www.php.net/manual/en/features.file-upload.post-method.php

Thanks for the reply but i really don't understand it. I don't know what or how im supposed to put it into an array. I tried to understand $_FILES function again but the examples make me more confused. I cant use the $_FILES function to move the text from the text box. I think i can understand how to get it from the array into the database but no idea how to get the text box data into the array.

The following is a stripped down version of your code, but using arrays for the form element names, based on the code example I posted a link to -

 

<?php
echo '<pre>Files:',print_r($_FILES,true),'</pre>'; // display the $_FILES array for demo purposes
echo '<pre>Post:',print_r($_POST,true),'</pre>'; // display the $_POST array for demo purposes

$upload_image_limit = 2; // How many images you want to upload at once

if($_SERVER['REQUEST_METHOD'] == "POST"){ // detect if a form was submitted
foreach ($_FILES["uplimg"]["error"] as $key => $error) { // loop over each error element
	if ($error == UPLOAD_ERR_OK) { // if no error (the file uploaded correctly)
		$tmp_name = $_FILES["uplimg"]["tmp_name"][$key]; // reference the temp_name
		$name = $_FILES["uplimg"]["name"][$key]; // reference the name
		$caption = $_POST['cap'][$key];
		// perform other validation tests here....

		// process the uploaded file and caption information here....
		echo "Name: $name, Caption: $caption<br />";
	}
}
}

############################### HTML FORM
$i = 0;
$form_img = '';
while($i++ < $upload_image_limit){
$form_img .= "<label>Image $i: </label> <input type='file' name='uplimg[$i]'><br /> <input type='text' name='cap[$i]' value='cap$i'><br />\n";
}
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';
echo $htmo;
?>

You, my friend, are amazing. It took me a bit of time to work out how to put the rest of my bits in there but it works perfect!  This is what i ended up with just so people can see (Only from the upload down)

 

##################### UPLOAD SCRIPT


if($_SERVER['REQUEST_METHOD'] == "POST"){ // detect if a form was submitted
foreach ($_FILES["uplimg"]["error"] as $key => $error) { // loop over each error element
	if ($error == UPLOAD_ERR_OK) { // if no error (the file uploaded correctly)
		$tmp_name = $_FILES["uplimg"]["tmp_name"][$key]; // reference the temp_name
		$name = $_FILES["uplimg"]["name"][$key]; // reference the name
		$caption = $_POST['cap'][$key];
		// perform other validation tests here....
                        // process the uploaded file and caption information here....
                        $img_path = $upload_dir.$name;
                        copy($tmp_name, $img_path );
                        if($enable_thumbnails) make_thumbnails($thumb_dir, $name);
		echo "Name: $name, Caption: $caption, <br />";

                        include ('db.php');
                        $con = mysql_connect("$host","$username","$password");
                        if (!$con)
                          {
                          die('Could not connect: ' . mysql_error());
                          }mysql_select_db("erikee10_eric", $con);

                        $sql="INSERT INTO photos (address, cap)
                        VALUES
                        ('$name', '$caption')";

                        if (!mysql_query($sql,$con))
                          {
                          die('Error: ' . mysql_error());
                          }

	}
}
}

############################### HTML FORM
$i = 0;
$form_img = '';
while($i++ < $upload_image_limit){
$form_img .= "<label>Image $i: </label> <input type='file' name='uplimg[$i]'><br /> 
Caption: <input type='text' name='cap[$i]' value='cap$i'><br /><br />\n";
}
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';
echo $htmo;

 

Having these displayed

 

echo '<pre>Files:',print_r($_FILES,true),'</pre>'; // display the $_FILES array for demo purposes
echo '<pre>Post:',print_r($_POST,true),'</pre>'; // display the $_POST array for demo purposes

 

Really helped me understand arrays and the $_FILES function alot better!

 

 

Thanks again

Eric

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.