...

View Full Version : File upload, create a thumbnail too an place into thumbnail folder



jarv
11-11-2011, 05:16 PM
My current code uploads images to the gallery folder, I would like to also get the image uploaded and create a thumbnail from it too but place in the thumbnails folder and update datebase too

thanks



$FileName = uniqid() .'-' .$_FILES['file']['name'];
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $FileName . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";


if (file_exists("gallery/" . $FileName))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"gallery/" . $FileName);

// Define $myusername and $mypassword
$UserID=$_POST['UserID'];
$PictureName=$_POST['PictureName'];
$PictureDate=$_POST['PictureDate'];
$TargetID=$_POST['TargetID'];

// To protect MySQL injection (more detail about MySQL injection)
$UserID = stripslashes($UserID);
$PictureName = stripslashes($PictureName);
$PictureDate = stripslashes($PictureDate);
$TargetID = stripslashes($TargetID);
$UserID = mysql_real_escape_string($UserID);
$PictureName = mysql_real_escape_string($PictureName);
$PictureDate = mysql_real_escape_string($PictureDate);
$TargetID = mysql_real_escape_string($TargetID);


$sql = "INSERT INTO rstargetpictures (UserID, FileName, PictureName, PictureDate, TargetID)
VALUES ('$UserID', '$FileName', '$PictureName', '$PictureDate', '$TargetID')";
$msg = "New booking added";
$result = mysql_query($sql) or die('Error: ' . mysql_error() . '<br>SQL: ' . $sql);

echo "Stored in: " . "gallery/" . $FileName;
}
}
}
else
{
echo "Invalid file";
}

mlseim
11-11-2011, 06:21 PM
Here you go ... see script below.

Make a subdirectory called /gallery/thumbs/
That is where the thumbnail gets saved.
The filename will be the same as the fullsize, but in the /thumbs/ directory.

I added a function to make+save the thumbs, and set the size to 100 (you can change that).
I'm not the author of this function ... I just use it all the time because it works so good.
That resize function is a nice one to save in your "snippets" folder for use on other scripts.




<?php

$FileName = uniqid() .'-' .$_FILES['file']['name'];
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $FileName . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";


if (file_exists("gallery/" . $FileName))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"gallery/" . $FileName);

// Resize the original file to a thumbnail
// Maximum width of 100.
// Saved with the same filename, but in the "thumbs" directory.
resize("gallery/".$FileName, 100, "thumbs/".$FileName);

// Define $myusername and $mypassword
$UserID=$_POST['UserID'];
$PictureName=$_POST['PictureName'];
$PictureDate=$_POST['PictureDate'];
$TargetID=$_POST['TargetID'];

// To protect MySQL injection (more detail about MySQL injection)
$UserID = stripslashes($UserID);
$PictureName = stripslashes($PictureName);
$PictureDate = stripslashes($PictureDate);
$TargetID = stripslashes($TargetID);
$UserID = mysql_real_escape_string($UserID);
$PictureName = mysql_real_escape_string($PictureName);
$PictureDate = mysql_real_escape_string($PictureDate);
$TargetID = mysql_real_escape_string($TargetID);


$sql = "INSERT INTO rstargetpictures (UserID, FileName, PictureName, PictureDate, TargetID)
VALUES ('$UserID', '$FileName', '$PictureName', '$PictureDate', '$TargetID')";
$msg = "New booking added";
$result = mysql_query($sql) or die('Error: ' . mysql_error() . '<br>SQL: ' . $sql);

echo "Stored in: " . "gallery/" . $FileName;
}
}
}
else
{
echo "Invalid file";
}

function resize($img, $thumb_width, $newfilename){
$max_width=$thumb_width;

//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2')){
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}

//Get Image size info
list($width_orig, $height_orig, $image_type) = getimagesize($img);

switch ($image_type){
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img); break;
case 3: $im = imagecreatefrompng($img); break;
default: trigger_error('Unsupported filetype!', E_USER_WARNING); break;
}

/*** calculate the aspect ratio ***/
$aspect_ratio = (float) $height_orig / $width_orig;

/*** calulate the thumbnail width based on the height ***/
$thumb_height = round($thumb_width * $aspect_ratio);


while($thumb_height>$max_width){
$thumb_width-=10;
$thumb_height = round($thumb_width * $aspect_ratio);
}

$newImg = imagecreatetruecolor($thumb_width, $thumb_height);

/* Check if this image is PNG or GIF, then set if Transparent*/
if(($image_type == 1) OR ($image_type==3))
{
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);

//Generate the file, and rename it to $newfilename
switch ($image_type){
case 1: imagegif($newImg,$newfilename); break;
case 2: imagejpeg($newImg,$newfilename); break;
case 3: imagepng($newImg,$newfilename); break;
default: trigger_error('Failed resize image!', E_USER_WARNING); break;
}

return $newfilename;
}
?>





EDIT:
Also note ... looking at these lines of the script ...

move_uploaded_file($_FILES["file"]["tmp_name"],
"gallery/" . $FileName);

// Resize the original file to a thumbnail
// Maximum width of 100.
// Saved with the same filename, but in the "thumbs" directory.
resize("gallery/".$FileName, 100, "thumbs/".$FileName);

You might have a situation where your script does the move and tries to resize
without finishing the move instruction.

If that "timing issue" occurs, simply put the move command in an "if" statement.
The script must complete the move to determine "true" or "false", thus finishing the move.

Like this:

if(move_uploaded_file($_FILES["file"]["tmp_name"],
"gallery/" . $FileName)){
// let it finish the move
}

// Resize the original file to a thumbnail
// Maximum width of 100.
// Saved with the same filename, but in the "thumbs" directory.
resize("gallery/".$FileName, 100, "thumbs/".$FileName);




.

jarv
11-11-2011, 10:20 PM
Thanks,

I now get Invalid file displayed?!

here is my code



<?php
session_start();
mysql_connect("xxx", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$FileName = uniqid() .'-' .$_FILES['file']['name'];
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $FileName . "<br />";

if (file_exists("gallery/" . $FileName))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"gallery/" . $FileName);

// Resize the original file to a thumbnail
// Maximum width of 100.
// Saved with the same filename, but in the "thumbs" directory.
resize("gallery/".$FileName, 100, "thumbs/".$FileName);

// Define $myusername and $mypassword
$UserID=$_POST['UserID'];
$PictureName=$_POST['PictureName'];
$PictureDate=$_POST['PictureDate'];
$TargetID=$_POST['TargetID'];

// To protect MySQL injection (more detail about MySQL injection)
$UserID = stripslashes($UserID);
$PictureName = stripslashes($PictureName);
$PictureDate = stripslashes($PictureDate);
$TargetID = stripslashes($TargetID);
$UserID = mysql_real_escape_string($UserID);
$PictureName = mysql_real_escape_string($PictureName);
$PictureDate = mysql_real_escape_string($PictureDate);
$TargetID = mysql_real_escape_string($TargetID);


$sql = "INSERT INTO rstargetpictures (UserID, FileName, PictureName, PictureDate, TargetID)
VALUES ('$UserID', '$FileName', '$PictureName', '$PictureDate', '$TargetID')";
$msg = "New booking added";
$result = mysql_query($sql) or die('Error: ' . mysql_error() . '<br>SQL: ' . $sql);

echo "Stored in: " . "gallery/" . $FileName;
}
}
}
else
{
echo "Invalid file";
}

function resize($img, $thumb_width, $newfilename){
$max_width=$thumb_width;

//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2')){
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}

//Get Image size info
list($width_orig, $height_orig, $image_type) = getimagesize($img);

switch ($image_type){
case 1: $im = imagecreatefromgif($img); break;
case 2: $im = imagecreatefromjpeg($img); break;
case 3: $im = imagecreatefrompng($img); break;
default: trigger_error('Unsupported filetype!', E_USER_WARNING); break;
}

/*** calculate the aspect ratio ***/
$aspect_ratio = (float) $height_orig / $width_orig;

/*** calulate the thumbnail width based on the height ***/
$thumb_height = round($thumb_width * $aspect_ratio);


while($thumb_height>$max_width){
$thumb_width-=10;
$thumb_height = round($thumb_width * $aspect_ratio);
}

$newImg = imagecreatetruecolor($thumb_width, $thumb_height);

/* Check if this image is PNG or GIF, then set if Transparent*/
if(($image_type == 1) OR ($image_type==3))
{
imagealphablending($newImg, false);
imagesavealpha($newImg,true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);

//Generate the file, and rename it to $newfilename
switch ($image_type){
case 1: imagegif($newImg,$newfilename); break;
case 2: imagejpeg($newImg,$newfilename); break;
case 3: imagepng($newImg,$newfilename); break;
default: trigger_error('Failed resize image!', E_USER_WARNING); break;
}

return $newfilename;
}
?>

mlseim
11-11-2011, 10:31 PM
Did you create a directory called "thumbs"?

Oh, and I use a shared webhost online ...
You're using your own server? Are the / the wrong way ? /\/\/\ ??

jarv
11-11-2011, 11:05 PM
no no, it works but only with certain .jpg files?!

tangoforce
11-11-2011, 11:24 PM
As suggested to you earlier, have you tried debugging yet?

jarv
11-12-2011, 12:13 AM
hmm, how to debug that though?!

MattF
11-12-2011, 12:26 AM
echo.

jarv
11-12-2011, 12:28 AM
yeah, echo what though?! it's a JPG file... surely it should upload?!

tangoforce
11-12-2011, 01:36 AM
yeah, echo what though?! it's a JPG file... surely it should upload?!

Without a doubt the file HAS uploaded - the browser will do that automatically. The problem happens with the move_uploaded_file() function. If you don't get your filepaths correct then as soon as the script terminates, the files are deleted from the temp directory automatically by php.

Jarv, if you want to be a programmer, you MUST learn to debug your code. This is one of the very fundamentals of programming in any language. You can't just find bits of code and put them together and then get everyone else to fix them (well you can but eventually you will get let down).

You must learn to debug. Your post above where you say "hmm, how to debug that though?!" is the first sign of progress and its a good one. In all the months you've been here you're finally asking how to debug and thats good - very good.

Firstly you need to do this somewhere in your code to determine what the $_FILES array contains (such as temp names etc):

var_dump($_FILES);

That should give you the basics of what you need to know. The rest is pretty much the same thing- printing out variables to be sure that they contain the correct values that you think they should. Thats basically all that debugging is - printing values to check things are as they should.

When it comes to files, sometimes you need to run additional code - using if(file_exists()) and if (is_dir()) etc and then print out your yes/no values accordingly. You do it like this:



if (file_exists("gallery/" . $FileName))
{
echo $_FILES["file"]["name"] . " already exists. ";
}


That code came from YOUR code. THAT is how you debug but sometimes you have to debug every single line of code until you find the fault. Yes that can be hard work but it can save you the amount of time that you waste waiting for us to help you. You could fix it in an hour or two or wait 8-9 hours for us to help you. What is best?

You can also log things to a database for scripts that can't output anything and there are ways of doing that using var_export($Var, true); instead of var_dump().

I promise you jarv, once you've learnt the basics of debugging it gets a LOT easier :thumbsup:

mlseim
11-12-2011, 11:09 PM
Maybe you have differences in the extensions?

jpeg
jpg
JPG
Jpg
Jpeg

those are all different, case-sensitive.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum