Jump to content

move_uploaded_file() need some help


Go to solution Solved by jazzman1,

Recommended Posts

Hey guys,

Need a little help here, this function works fine the first time around, but I have added some logic to also create a thumbnail of the uploaded image.  the function is recursive and at the end calls itself, the problem is the second time around where the move_uploaded_file function fails.

 

Any help would be appreciated!

function imageUpload($file, $user, $isThumb = FALSE) {
	
	// create thumbnail or save picture
	if ($isThumb) {
		$userDirectory = $_SESSION['member_id'] . "/images/thumbs";
		$max = 100;
	} else {
		$userDirectory = $_SESSION['member_id'] . "/images";
		$max = 800;
	}
	
	/* For Debugging, this will properlly check to see if image has been selected
	if ($file['image']['name'] == "")
		throw new Exception ( 'No image selected' ); */
		
	// current directory
	$directory_self = str_replace ( basename ( $_SERVER ['PHP_SELF'] ), '', $_SERVER ['PHP_SELF'] );
	$upload_directory = $_SERVER ['DOCUMENT_ROOT'] . $directory_self . "$userDirectory/";
	$saveto = "$upload_directory" . time () . ".jpg";
	
	var_dump($saveto);
	echo "<br />";
	var_dump($file);
	echo "<br />";
	
	if (! makeDir ( "$upload_directory" ))
		throw new Exception ( 'Error creating location on server, please try again...' );
	
	if (! move_uploaded_file ( $file ['image'] ['tmp_name'], $saveto ))
		throw new Exception ( 'Error copying image to server, please try again...' );
	
	switch ($file ['image'] ['type']) {
		case 'image/gif' :
			$src = imagecreatefromgif ( $saveto );
			break;
		case 'image/jpeg' :
		case 'image/pjpeg' :
			$src = imagecreatefromjpeg ( $saveto );
			break;
		case 'image/png' :
			$src = imagecreatefrompng ( $saveto );
			break;
		default :
			// invalid image type
			throw new Exception ( 'Error, invalid file type.  Please upload only (.gif, .png or .jpg)' );
			break;
	}
	list ( $w, $h ) = getimagesize ( $saveto );
	
	$tw = $w;
	$th = $h;
	
	if ($w > $h && $max < $h) {
		$th = $max / $w * $h;
		$tw = $max;
	} elseif ($h > $w && $max < $h) {
		$tw = $max / $h * $w;
		$th = $max;
	} elseif ($max < $w) {
		$tw = $th = $max;
	}
	
	try {
		$tmp = imagecreatetruecolor ( $tw, $th );
		imagecopyresampled ( $tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h );
		imageconvolution ( $tmp, array (
				array (
						- 1,
						- 1,
						- 1 
				),
				array (
						- 1,
						16,
						- 1 
				),
				array (
						- 1,
						- 1,
						- 1 
				) 
		), 8, 0 );
		try {
			imagejpeg ( $tmp, $saveto );
		} catch (Exception $e) {
			throw new Exception('Error with function imagejpeg() ' . $e->getMessage());
		}
	} catch ( Exception $e ) {
		throw new Exception ( 'Error Code: ' . $e->getCode () );
	}
	
	try {
		if (!$isThumb) {
			echo "About to create thumbnail for image<br />";
			//create thumbnail for image
			$thumbLocation = imageUpload($file, $user, TRUE);
			var_dump($thumbLocation);
			$result = queryMySql ( "INSERT INTO pictures SET
				member_id='$user',
				file_location='$saveto',
				thumb_location='$thumbLocation'" );
			var_dump($result);
		} else{
			imagedestroy ( $tmp );
			imagedestroy ( $src );
		}
	} catch ( Exception $e ) {
		throw new Exception ( 'Unable to save to database: ' . $e->getCode () . " || " . $e->getMessage());
	}
	return $saveto;
}

Here is the output from my var_dump's and catch statements....

 

 

 

string(73) "/2/images/1381618929.jpg" 
array(1) { ["image"]=> array(5) { ["name"]=> string(10) "Desert.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpTKWhtS" ["error"]=> int(0) ["size"]=> int(845941) } } 
array(1) { ["image"]=> array(5) { ["name"]=> string(10) "Desert.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpTKWhtS" ["error"]=> int(0) ["size"]=> int(845941) } } 
About to create thumbnail for image
string(80) "/2/images/thumbs/1381618930.jpg" 
array(1) { ["image"]=> array(5) { ["name"]=> string(10) "Desert.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpTKWhtS" ["error"]=> int(0) ["size"]=> int(845941) } } 
array(1) { ["image"]=> array(5) { ["name"]=> string(10) "Desert.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpTKWhtS" ["error"]=> int(0) ["size"]=> int(845941) } } 
Failed to upload image Unable to save to database: 0 || Error copying image to server, please try again...

 

$file is $_FILES.....

 

any help would be greatly appreciated!

Link to comment
https://forums.phpfreaks.com/topic/282920-move_uploaded_file-need-some-help/
Share on other sites

Can I see the path to $upload_directory?

............................
$saveto = "$upload_directory" . time () . ".jpg";

// here
echo $upload_directory;

var_dump($saveto);
..........................

Also, don't understand very well what are you going to replace here ->

$directory_self = str_replace ( basename ( $_SERVER ['PHP_SELF'] ), '', $_SERVER ['PHP_SELF'] );
 
echo $directory_self;
Edited by jazzman1

That is funny, don't even remember coding this.....

$directory_self = str_replace ( basename ( $_SERVER ['PHP_SELF'] ), '', $_SERVER ['PHP_SELF'] );

still works fine with the first run again but fails on the second run to create a thumb....

	$upload_directory = $_SERVER ['DOCUMENT_ROOT'] . $_SERVER ['PHP_SELF'] . "$userDirectory/";
	$saveto = "$upload_directory" . time () . ".jpg"; 

var_dump

/home/(myusername)/(myDomain).com/2/images/1381624178.jpg"

took out my username and domain for security.....

Edited by JayStabins

Hm....it should be work. Just forget at now about the thumbnails.

Try to upload the same image twice recursively to two different directories.

I don't see anything wrong in this simple test:

function imageUpload($file, $user, $isThumb = FALSE) {
	
	// create thumbnail or save picture
	if ($isThumb) {
		$userDirectory = 'jazzman' . "/images/thumbs";
		$max = 100;
	} else {
		$userDirectory = "jazzman" . "/images";
		$max = 800;
	}
	
	// current directory
	$directory_self = str_replace ( basename ( $_SERVER ['PHP_SELF'] ), '', $_SERVER ['PHP_SELF'] );

	$upload_directory = $_SERVER ['DOCUMENT_ROOT'] . $directory_self . "$userDirectory/";
                
        var_dump($upload_directory );
        
        echo "<br />";
        
       var_dump($file,$user,$isThumb);
        
		if (!$isThumb) {
			echo "About to create thumbnail for image<br />";
			//create thumbnail for image
			$thumbLocation = imageUpload($file, $user, $isThumb = TRUE);
                        
                        } 
}

imageUpload('jazzman.jpg', 'jazz');

Output:

 

 

string(40) "/var/www/html/test/jazzman/images/"
string(11) "jazzman.jpg" string(4) "jazz" bool(false)
About to create thumbnail for image
string(47) "/var/www/html/test/jazzman/images/thumbs/"
string(11) "jazzman.jpg" string(4) "jazz" bool(true)

  • Solution

When you submit the form this form has been submitted ones! So the file has been already submitted. When you're calling this function again the first argument does not exist (no resource). The first argument should be the path to the large image not just the name of the file as expected to be.

$thumbLocation = imageUpload('path_to_the_uploaded_file', $user, $isThumb = TRUE);
Edited by jazzman1

You nailed it, once I use the move_uploaded_file function I lose the file from the $_POST, so I passed the file location instead when calling the function again.  I put some checks in the function to ensure that the file location is being used properly and also the switch statement is now nested (because I am using the function for one purpose) and now it works flawlessly.  Here it he script for anyone that may want to use it to create a thumb and an image from one uploaded file.

 

Cheers!

function imageUpload($file, $user, $isThumb = FALSE) {
	
	// create thumbnail or save picture
	if ($isThumb) {
		$userDirectory = $_SESSION ['member_id'] . "/images/thumbs";
		$max = 100;
	} else {
		$userDirectory = $_SESSION ['member_id'] . "/images";
		$max = 800;
	}
	
	$directorySelf = $_SERVER ['PHP_SELF'];
	$upload_directory = $_SERVER ['DOCUMENT_ROOT'] . $directorySelf . "$userDirectory/";
	$saveto = "$upload_directory" . time () . ".jpg";
	
	if (! makeDir ( "$upload_directory" ))
		throw new Exception ( 'Error creating location on server, please try again...' );
	
	if ($isThumb) {
		echo "About to try and copy " . $file . " to " . $saveto;
		copy ( $file, $saveto );
		$src = imagecreatefromjpeg ( $saveto );
	} else {
		if (! move_uploaded_file ( $file ['image'] ['tmp_name'], $saveto ))
			throw new Exception ( 'Error copying image to server, please try again...' );
		
		switch ($file ['image'] ['type']) {
			case 'image/gif' :
				$src = imagecreatefromgif ( $saveto );
				break;
			case 'image/jpeg' :
			case 'image/pjpeg' :
				$src = imagecreatefromjpeg ( $saveto );
				break;
			case 'image/png' :
				$src = imagecreatefrompng ( $saveto );
				break;
			default :
				// invalid image type
				throw new Exception ( 'Error, invalid file type.  Please upload only (.gif, .png or .jpg)' );
				break;
		}
	}


	list ( $w, $h ) = getimagesize ( $saveto );
	
	$tw = $w;
	$th = $h;
	
	if ($w > $h && $max < $h) {
		$th = $max / $w * $h;
		$tw = $max;
	} elseif ($h > $w && $max < $h) {
		$tw = $max / $h * $w;
		$th = $max;
	} elseif ($max < $w) {
		$tw = $th = $max;
	}
	
	try {
		$tmp = imagecreatetruecolor ( $tw, $th );
		imagecopyresampled ( $tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h );
		imageconvolution ( $tmp, array (
				array (
						- 1,
						- 1,
						- 1 
				),
				array (
						- 1,
						16,
						- 1 
				),
				array (
						- 1,
						- 1,
						- 1 
				) 
		), 8, 0 );
		try {
			imagejpeg ( $tmp, $saveto );
		} catch ( Exception $e ) {
			throw new Exception ( 'Error with function imagejpeg() ' . $e->getMessage () );
		}
	} catch ( Exception $e ) {
		throw new Exception ( 'Error Code: ' . $e->getCode () );
	}
	
	try {
		if (! $isThumb) {
			echo "About to create thumbnail for image<br />";
			// create thumbnail for image
			$thumbLocation = imageUpload ( $saveto, $user, TRUE );
			$result = queryMySql ( "INSERT INTO pictures SET
				member_id='$user',
				file_location='$saveto',
				thumb_location='$thumbLocation'" );
			var_dump ( $result );
		} else {
			imagedestroy ( $tmp );
			imagedestroy ( $src );
		}
	} catch ( Exception $e ) {
		throw new Exception ( 'Unable to save to database: ' . $e->getCode () . " || " . $e->getMessage () );
	}
	return $saveto;
}
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.