Hi all!

Im making an upload script that uploads an image file, saves it and saves a thumbnail copy in a different directory.

I have tried a couple of scripts and have found one which I think will work nicely but i cannot get it working.

The script is below:

<?php
//get values for other required vars
$filename = $_POST['uploadfile'];  //origional filename
$filetype = $_FILES['uploadfile']['type']; //uploaded filetype
$filesize = $_FILES['uploadfile']['size']; //uploaded file size
$filenametmp = $_FILES['uploadfile']['tmp_name']; //uploaded file's server side temporary name

$uploaddir = '../images/'; //upload directory
$uploadfile = $uploaddir.$iid.basename($_FILES['uploadfile']['name']); //upload directory + rand + origional name

$size = getimagesize($filenametmp);
$width = $size[0];
$height = $size[1];

//get file extension for validation
$ext = strrchr($file_name,'.');
$ext = strtolower($ext);
$limitedext = array(".gif",".jpg",".png",".jpeg",".bmp");	
$getExt = explode ('.', $filename);
$file_ext = $getExt[count($getExt)-1];

//set width variables
$ThumbWidth = 80;

	if($filesize){
		//keep image type
		if($file_type == "image/pjpeg" || $filenametmp == "image/jpeg" || $filenametmp == "image/jpg")
		{$new_img = imagecreatefromjpeg($filenametmp);}
		
		elseif($file_type == "image/x-png" || $filenametmp == "image/png")
		{$new_img = imagecreatefrompng($filenametmp);}
		
		elseif($file_type == "image/gif")
		{$new_img = imagecreatefromgif($filenametmp);}		
	}//if


		//make width and height array from getimagesize returned array
		list($width, $height) = getimagesize($filenametmp);
		
		//calculate the image ratio
		$imgratio=$width/$height;
		if ($imgratio>1){
		$newwidth = $ThumbWidth;
		$newheight = $ThumbWidth/$imgratio;}
		else{
		$newheight = $ThumbWidth;
		$newwidth = $ThumbWidth*$imgratio;}
		
		//resize image.
		$resized_img = imagecreatetruecolor($newwidth,$newheight);
				
		//the resizing is going on here!
		//error 1 results from the line below:
		imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
		
		//finally, save the image
		ImageJpeg ($resized_img,"../thumbs/".$iid.$file_ext);
		ImageDestroy ($resized_img);
		//error 2 results form the line below:
		ImageDestroy ($new_img);
		
		move_uploaded_file ($filenametmp, "../images/".$iid.$file_ext);
?>

The errors are:

error #1:
Warning: imagecopyresized(): supplied argument is not a valid Image resource in /home/sites/ on line 120

error#2:
Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/sites/ on line 125

I hope somebody can help, iv spent aaages on trying to get something working xD

Thanks in advance,

Max :)

Dani AI

Generated

A short diagnosis and checklist for the specific warnings shown here: those messages mean GD never returned a valid image resource, so imagecopy* and imagedestroy were handed a non-image value. In practice that happens for three reasons: variable/name bugs (as noted), the uploaded file was not actually readable or the upload failed, or GD on the server cannot create the image (missing/unsupported format). ’s fix by correcting permissions confirms a file-read/permission problem in this case.

Steps to isolate and fix the issue

  • Confirm the upload actually succeeded: check $_FILES['uploadfile']['error'] and that is_uploaded_file($tmp_name) and is_readable($tmp_name) are true. See PHP file upload docs: Handling file uploads and is_uploaded_file.
  • Use getimagesize() on the uploaded temp file to get width, height and the reliable mime value; base format handling on that, not $_FILES['type']. See getimagesize.
  • Before calling imagecopyresampled/imagecopyresized or imagedestroy, verify the imagecreatefrom* call returned a valid image resource (bail with a clear error if it returned false). Check the server supports the needed handlers (JPEG/PNG/GIF) via phpinfo() or [function_exists] checks and the GD manual: GD library.
  • Ensure upload and target directories are writable by PHP. Prefer directory perms 0755 and file perms 0644; avoid 0777. Use is_writable to test.

Additional practical notes

  • Prefer imagecopyresampled for quality and handle PNG/GIF transparency (imagesavealpha, proper blending) when needed. See imagecopyresampled.
  • Use pathinfo() to obtain and normalize extensions, sanitize filenames, and never trust user-supplied names for security: pathinfo.
  • Turn on full error reporting while debugging and check PHP/webserver logs; switch display off in production.

Following those checks will make the cause obvious: either a variable/logic bug, a permissions/readability problem, or missing GD support.

Recommended Answers

All 2 Replies

Hi.

You seem to mix up your variables a lot. You define them using one name and then try to use them using another.
And you are validating the image based on the extension, which is pretty much useless. Validating the mime type returned by the getimagesize function is a lot more reliable.

This is a modified version of code I have used in the past.
It should do pretty much the same thing yours is meant to do:

<?php
header("Content-Type: text/plain");

// Validate upload
if(!isset($_FILES['uploadfile'])){
	die("File was not uploaded");
}
if($_FILES['uploadfile']['error'] != 0){
	die("File upload failed. (Code #". $_FILES['uploadfile']['error'] .")");
}

// Set and validate the file directory info
$uploadDir = "/path/to/upload/dir/";
$originalDir = $uploadDir . "originals/";
$thumbDir = $uploadDir . "thumbs/";
if(!is_writable($originalDir) || !is_writable($thumbDir)) {
	die("PHP does not have permission to write to the upload directories.");
}

// Get and validate the uploaded image information
$image = $_FILES['uploadfile'];
$imageInfo = getimagesize($image['tmp_name']);
$allowedMime = array("image/jpeg", "image/png", "image/gif");
if(!in_array($imageInfo['mime'], $allowedMime)) {
	die("Image Mime type is not allowed (". $imageInfo['mime'] .")");
}

// Move the original to it's new location
$originalPath = $originalDir . $image['name'];
if(!move_uploaded_file($image['tmp_name'], $originalPath)) {
	die("Failed to move the original image");
}

// Load the original into a GD object
switch ($imageInfo['mime']) {
	case "image/jpeg":
		$originalImage = imagecreatefromjpeg($originalPath);
		break;
	case "image/png":
		$originalImage = imagecreatefrompng($originalPath);
		break;
	case "image/gif":
		$originalImage = imagecreatefromgif($originalPath);
		break;
	// No default because the above mime check makes sure it isn't needed
}

// Calculate the thumb size
$thumbMaxSize = 80;
$originalRatio = $imageInfo[1] / $imageInfo[0];
if($originalRatio < 0) {
	$thumbWidth = $thumbMaxSize;
	$thumbHeight = $thumbMaxSize * $originalRatio;
}
else {
	$thumbHeight = $thumbMaxSize;
	$thumbWidth = $thumbMaxSize / $originalRatio;
}

// Create the thumb
$thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);
if(!imagecopyresampled($thumbImage, $originalImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imageInfo[0], $imageInfo[1])){
	die("Failed to create the thumb");
}

// Save the thumb
$thumbPath = $thumbDir . "thumb_" . $image['name'];
switch ($imageInfo['mime']) {
	case "image/jpeg":
		imagejpeg($thumbImage, $thumbPath);
		break;
	case "image/png":
		imagepng($thumbImage, $thumbPath);
		break;
	case "image/gif":
		imagegif($thumbImage, $thumbPath);
		break;
}

// Delete resources
imagedestroy($thumbImage);
imagedestroy($originalImage);

// Show success message
echo "Upload complete";
?>

ahh fantastic, thanks for the script. I think I just dived in head first without trying to understand whats happening where first which is why my variables were so scrambled.

just incase anybody else wants to use the script I changed the permissions on my files to 755 and it worked great :)

Thanks again, much appreciated.

Max

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.