Temp file behaviour on upload

Hi there,

I am writing a controller to handle uploads. I want to save uploaded images and create a thumbnail of them so that I can display a list of the uploaded images, with a thumbnail so that the user has a visual reminder of what the image is.

So the controller script is meant to create a thumbnail form the uploaded temp file, then store the filename and thumbnail’s filename into a database table, then copy the two image files into the uploads folder onto the server.

The only problem I’m getting is that the thumbnail cannot be copied to the uploads directory, because it doesn’t exist. I’m not sure why.

Here’s an excerpt of the controller code which deals with the thumbnail creation:


// Create a thumbnail
$thumbwidth = 200;
$thumbheight = 200;
$dims = getimagesize($_FILES['upload']['tmp_name']);
[B]$thumb = imagecreatetruecolor($thumbwidth, $thumbheight);[/B]

//Run checks to make sure correct function is used
if ($type == 'png')
{
  $original = imagecreatefrompng($tempname);
  imagecopyresampled($thumb, $original, 0, 0, 0, 0, $thumbwidth, $thumbheight, $dims[0], $dims[1]);
}
	  
if ($type == 'jpg')
{
  $original = imagecreatefromjpeg($tempname);
  imagecopyresampled($thumb, $original, 0, 0, 0, 0, $thumbwidth, $thumbheight, $dims[0], $dims[1]);
}
	  
if ($type == 'gif')
{
  $original = imagecreatefromgif($tempname);
  imagecopyresampled($thumb, $original, 0, 0, 0, 0, $thumbwidth, $thumbheight, $dims[0], $dims[1]);
}
	
$thumbname = $filename . 'thumb.' . $type;
$filename = $filename . '.' . $type;
	
//Copy temp file to server
if(!copy($tempname, $uploaddir . $filename))
{
  $message = 'Unable to copy uploaded file to server! ';
} else {
  $message = 'Upload sucessfully copied to the server. ';
}
	
if(!copy($thumb, $uplaoddir . $thumbname))
{
  $message .= 'Unable to copy thumbnail to server!';
} else {
  $message .= 'Thumbnail sucessfully copied to the server.';
}

The way I am dealing with the thumbnail image is with the $thumb string, which is holding the result of the createimagetruecolor() function. My first thought is that that would not be suitable as a filename for the copy function. If so, how would I give it a suitable filename?

Thanks in advance for your help,
Mike

Not sure if this is the most elegant way around this problem, but discovered that there are a number of functions to output an image to a file:

imagepng();
imagejpeg();
imagegif();

more info on imagepng here:
http://uk.php.net/manual/en/function.imagepng.php

you can supply a filename for the file to be written to as the second argument, so using my code as an example:


imagepng($thumb, $uploaddir . $thumbname);

creates the file in /uploads with the name ($filename)thumb.png.

Case closed.
(: