Problem accessing Array

I appreciate your well-thought-out solution above, but you made the assumption I know OOP…

Will have to save that for another day, but thanks!

Debbie

@DoubleDee

Just to backup what @ServerStorm said, just the very fact that you even know that dealing with uploaded files is dangerous puts you light years ahead of many other developers. Keep plugging away. I do have a few more thoughts on security but again, get your code going.

Just got back from a quick supper…

Thanks for the kind words. (Everyone else has been making me feel like I’m “lazy” and an “idiot” so I’m not having a good day…

Please stick with it.

I am trying, but week’s like this where I have nothing to show for my efforts makes me feel like I don’t have what it takes to build my own website… :frowning:

I wrote the object for you so that you can handle the properties more cleanly and consistently. You don’t have to mess around with array indexes as much.

As just mentioned, I’m sorry to “look a gift-horse in the mouth”, but I’m not ready for OOP. (If you can help me fix my existing Procedural code, that would be welcome!

I am sure that you are already doing so, but make sure you validate the paths of the images ($tempFile) that you are passing into getImageSize($tempFile),because you are doing this secure, I am sure that you are not running your upload.php in the same folder where the images are located, so a bad path or weird characters could cause the file to fail, thus rendering an error.

I don’t have any error-handling for the path to the images. Guess that is another I need to do.

As far as directory structure, that is a whole other topic I need advice on?!

Right now, I have my Document Root and in it I have a “members” folder which contains “upload.php” and then I have an “uploads” folder which is where I was thinking of putting Users’ photos, although in all of my reading the last several days, some people say you should store photos OUTSIDE OF the Web Root and only allow access to them through a function. (I’m very curious about this…)

Also, for everyone’s advice, realize that I have a VPS but have virtually no Linux or System Admin experience, so I need secure yet reasonable solutions…

I’m sorry you are frustrated… hopefully we on this forum do not further add to your confusion; although this can be hard as we all have our own ways, beliefs and experience.

Regards,
Steve

Thanks for the kind words.

Up until this afternoon, I thought I was making good progress until DeathShadow “exposed” my newbie coding… :frowning:

Debbie

Just got back from a quick supper…

Thanks for the kind words. (Everyone else has been making me feel like I’m “lazy” and an “idiot” so I’m not having a good day…

Please stick with it.

I am trying, but week’s like this where I have nothing to show for my efforts makes me feel like I don’t have what it takes to build my own website… :frowning:

I wrote the object for you so that you can handle the properties more cleanly and consistently. You don’t have to mess around with array indexes as much.

As just mentioned, I’m sorry to “look a gift-horse in the mouth”, but I’m not ready for OOP. (If you can help me fix my existing Procedural code, that would be welcome!

I am sure that you are already doing so, but make sure you validate the paths of the images ($tempFile) that you are passing into getImageSize($tempFile),because you are doing this secure, I am sure that you are not running your upload.php in the same folder where the images are located, so a bad path or weird characters could cause the file to fail, thus rendering an error.

I don’t have any error-handling for the path to the images. Guess that is another I need to do.

As far as directory structure, that is a whole other topic I need advice on?!

Right now, I have my Document Root and in it I have a “members” folder which contains “upload.php” and then I have an “uploads” folder which is where I was thinking of putting Users’ photos, although in all of my reading the last several days, some people say you should store photos OUTSIDE OF the Web Root and only allow access to them through a function. (I’m very curious about this…)

Also, for everyone’s advice, realize that I have a VPS but have virtually no Linux or System Admin experience, so I need secure yet reasonable solutions…

I’m sorry you are frustrated… hopefully we on this forum do not further add to your confusion; although this can be hard as we all have our own ways, beliefs and experience.

Regards,
Steve

Thanks for the kind words.

Up until this afternoon, I thought I was making good progress until DeathShadow “exposed” my newbie coding… :frowning: :frowning:

Debbie

Might be time to give a good hard look at learning it – shame PHP is the LAST place I’d suggest learning OOP concepts, but since it’s model is so hopelessly crippled unless you plan on using some other language in the future, might as well start here.

It’s not the be-all end-all solution many people claim it is – I’ve grown weary of dealing with code where even the most mundane of things is thrown inside an object, but in this case an object based handler for what you’re doing may indeed be your best bet for handling it as it would… greatly simplify the process.

Gimme a few minutes and I’ll toss together an example object that’s drop-in code for you – it will combine a lot of your different threads about this into one codebase – checking if GD is installed, checking if the image is an image, resizing it, and finally saving a resized copy that will fit inside a maximum specified dimensions. (without any extra padding/background around it)… for an old salt like me that’s ten or fifteen minutes worth of code; particularly as a object… I’ll give it some nice error handling logic while at it.

Really if you’re thinking security anyways you should be learning objects to use PDO… or at the very least mysqli “properly” instead of sticking with the slow procedural wrappers.

Wow DD, don’t know what happened here but your last post seems to have borked the whole thread… I’m flagging my own post in the hopes maybe a mod can edit out whatevers messed up.

This is a bit rough around the edges, but keeps things fairly simple… showing just exactly why objects are a pretty good idea on something like this with their own namespace, things like constructors, etc, etc, etc…

imageHandling.php


<?php

class imageUploadHandler {
	public
		$fileName,
		$loaded=false,
		$errors=array(),
		$reportedWidth=0,
		$reportedHeight=0,
		$sourceWidth=0,
		$sourceHeight=0,
		$sourceFormat,
		$resultWidth=0,
		$resultHeight=0;
		
	private
		$formats=array(
			IMAGETYPE_GIF  => 'imagecreatefromgif',
			IMAGETYPE_JPEG => 'imagecreatefromjpeg',
			IMAGETYPE_PNG  => 'imagecreatefrompng'
		),
		$sourceImage,
		$resultImage;

	public function __construct($fileName) {
		if (extension_loaded('gd') && function_exists('gd_info')) {
			if (
				file_exists($fileName) &&
				($temp=@getimagesize($fileName))
			) {
				list(
					$this->reportedWidth,
					$this->reportedHeight,
					$tempFormat
				)=$temp;
				if (isset($this->formats[$tempFormat])) {
					$this->sourceFormat=$tempFormat;
					$this->fileName=$fileName;
				} else $this->errors[]='Unsupported file format';
			} else $this->errors[]='Invalid file or file format';
		} else $this->errors[]='GD Image module not found, PHP cannot process images';
	} // __construct
	
	public function readFromSource() {
		if (count($this->errors)>0) {
			$this->errors[]='Attempt to load invalid file';
			return false;
		}
		$this->sourceImage=$this->formats[$this->sourceFormat]($this->fileName);
		$this->sourceWidth=imagesx($this->sourceImage);
		$this->sourceHeight=imagesy($this->sourceImage);
		return ($loaded=true);
	} // readFromSource
	
	public function resize($maxWidth,$maxHeight) {
		if (count($this->errors)>0) {
			$this->errors[]='Attempt to resize invalid file';
			return false;
		} if ($this->loaded || $this->readFromSource()) {
			if ($this->sourceWidth>$maxWidth) {
				$this->resultHeight=floor($this->sourceHeight*$maxWidth/$this->sourceWidth);
				if ($this->resultHeight>$maxHeight) {
					$this->resultWidth=floor($this->sourceWidth*$maxHeight/$this->sourceHeight);
					$this->resultHeight=$maxHeight;
				} else $this->resultWidth=$maxWidth;
			} else if ($this->sourceHeight>$maxHeight) {
				$this->resultWidth=floor($this->sourceWidth*$maxHeight/$this->sourceHeight);
				$this->resultHeight=$maxHeight;
			} else { /* smaller than max, leave it alone! */
				$this->resultWidth=$this->sourceWidth;
				$this->resultHeight=$this->sourceHeight;
			}
			$this->resultImage=imagecreatetruecolor($this->resultWidth,$this->resultHeight);
			imagecopyresampled(
				$this->resultImage,$this->sourceImage,
				0,0,
				0,0,
				$this->resultWidth,$this->resultHeight,
				$this->sourceWidth,$this->sourceHeight
			);
			return true;
		} else {
			$this->errors[]='Unable to resize invalid file';
			return false;
		}
	} // resize
	
	/*
		fileNameRoot should be path and name without extension
		Extension will be auto-set by output format
		compression should be a value 0..100, routine will
		convert value as appropriate to each save routine.
	*/
	public function writeToFile($fileNameRoot,$format,$compression=100) {
		if (count($this->errors)>0) {
			$this->errors[]='Attempt to resize invalid file';
			return false;
		}
		if ($this->resultWidth==0) {
			$this->errors[]='Attempt to write unprocessed image';
			return false;
		}
		switch ($format) {
			case IMAGETYPE_GIF:
				imagegif($this->resultImage,$fileNameRoot.'.gif');
			break;
			case IMAGETYPE_PNG:
				imagepng(
					$this->resultImage,
					$fileNameRoot.'.png',
					round($compression*0.9)
				);
			break;
			case IMAGETYPE_JPG:
				imagejpeg(
					$this->resultImage,
					$fileNameRoot.'.jpg',
					100-$compression
				);
			break;
			default:
				$this->errors[]='Unable to save, unsupported format';
				return false;
		}
		return true;
	} // writeToFile
	
	/*
		error report will output a header and the errors if any, returning true
		returns false if no errors present.
	*/
	public function errorReport() {
		if (count($this->errors)==0) return false;
		echo '
			<h1>There were errors attempting to process the image.</h1>
			<ul class="errors">';
		foreach ($this->errors as $error) {
			echo '
				<li>',$error,'</li>';
		}
		echo '
			</ul>';
		return true;
	} // errorReport
	
}

?>

Since you said you didn’t know objects, I’ll take the time to run it down ‘simple’ for you with lots of similes and comparisons that should make it easier to grasp than, well… most texts on the subject.

Using that isn’t too hard… first you need to make a variable be an ‘instance’ of that class – “classes”, aka an object definition, defines what an object of that ‘type’ can contain for values and do for ‘methods’ – methods being functions specific to JUST that object. This is actually easier to grasp in languages like Pascal or C where you have “strict typecasting” and complex structures like STRUCT or RECORD. Closest you have in PHP to a object is an array… think of all those ‘public’ variables as being like associative array indexes – then picture all the ‘methods’ (function declarations) as if they too were associative array values that just happen to be functions instead of values. (javascript can actually do that)… public just means everyone can see it/access it, private means it can only be seen/used by the object itself… pretty simple.

You would create this object handler thus:

$image=new imageUploadHandler(‘test1.png’);

When you do a ‘new’ it creates a new ‘object’ with $image basically as a pointer/handler for that object – much like how you would use a $result handler in normal mysql_ functions. When you ‘new’ an object the ‘method’ (function) that is called is referred to as the ‘constructor’ – in PHP the constructor is always called __construct… which if we look up above:

public function __construct($fileName) {

The constructor takes the filename of the image you want to check, resize and copy.

Once you have $image created as a new object of the imageUploadHandler class, I suggest calling it’s errorReport method do see if anything went wrong. If you not the result, the method will output errors and you can use the positive result to continue.

if (!$image->errorReport()) {

Since it loaded ok, you could then call the resizer. Its method declaration:

public function resize($maxWidth,$maxHeight) {

means all we need to pass it is the maximum width and height:

$image->resize(160,244);

I made the resizer a separate method so that if you wanted you could load the image once (with the readFromSource method or let resize automatically call it the first time) and then create multiple different sizes to be saved.

I would then run the error report again (just to be sure) and proceed on to writing it to a file. It’s method declaration:

public function writeToFile($fileNameRoot,$format,$compression=15) {

means we just pass it the path/filename to write it to WITHOUT an extension, the file format using the EXIF IMAGETYPE_ constants, and a compression rate. I made the rate 0 to 100, 0 being the least, 100 being the most, and then have the routine change it to fit each image format’s possible results… so we can call it thus:

$image->writeToFile(‘new’,IMAGETYPE_JPEG,25);
// 25% lossy JPEG

or thus:

$image->writeToFile(‘new’,IMAGETYPE_PNG,100);
// maximum compression, lossless 24 bit png

Having writeToFile be it’s own method means you could also use it to write to more than one file format… this can be handy as you can test writing to say… three different formats and then see which one is the smallest.

Though for avatars, 15% JPEG is probably your best bet in terms of predictable size.

So alltogether a demo program would look something like this:


<?php

require_once('imageHandling.php');

$image=new imageUploadHandler('test1.png');
if (!$image->errorReport()) {
	$image->resize(160,244);
	if (!$image->errorReport()) {
		$image->writeToFile('images/new',IMAGETYPE_JPEG,15);
		if (!$image->errorReport()) {
			echo '
				<h1>Image converted ok</h1>
				<p>There were no errors reported during conversion</p>
				<img src="images/new.jpg" alt="resulting image" />';
		}
	}
}

?>

Which would turn test1.png into images/new.jpg… resizing it to fit aspect correct as smaller than the maxWidth or maxHeight sent to the ::resize method – throwing all the appropriate errors if anything goes awry along the way.

Took me longer to write this explanation than to code it :smiley:

@DoubleDee
Actually, making use of objects is very little difference from when you use regular PHP library functions. Programming using OOP has a significant learning curve, but using objects do not.

To instantiate an Object you use new.
So $info = new InfoObj(); creates an instance of the ‘blue-print’ InfoObj class.
The InfoObj class may have public functions (called methods) that you can use. In this example InfoObj has a getInfoAsString() public method (function).
To use the result of getInfo() you reference the Object: $info-> getInfoAsString(); the -> instructs the object to call the getInfoAsString() method. Presumably getInfoAsString returns the info as a string.

Generally it is not necessary to know how an object is programmed, you only need to know what public interface (functions) it has and use them. Often you have to pass data into an object so in post 13 and in DeathShadows60’s class in post 27 you pass data in.

So in post 13 as it is a simpler class you:
$imageValues = new ImageValues(); // instantiate the object - this object has two public methods setImageProperties(Array $imageValues), and __get(‘key string’)
Give the object your image data array that $img_data = getImageSize($tempFile) creates, using $imageValues->setImagePropertiesCOLOR=#007700
then you can use the $imageValues-> __get(‘mime’) to get the image properties.

See using objects are no more or less complicated than using php library function like getImageSize($tempFile).

Regards,
Steve
[/COLOR]

** MODS: Everytime I hit “Reply with Quote” in this thread I get a white screen where I would normally type. The entire thread must be corrupt?! ***

As if that wasn’t enough…

Some things as I play “catch up” since I was locked out of SitePoint last night…

1.) I feel like crying after a really bad week with no workable code to show for my efforts

2.) I appreciate everyone trying to help

3.) Some great suggestions out there, but I ask that we press “Pause” on many of them. (For example, not isn’t a good time to teach me OOP.)

4.) I am overwhelmed right now, and this thread is morphing. I could use some help rewinding and addressing one issue at a time.

Thanks,

Debbie

** MODS: I can’t quote anyone which makes responding to people a real manual pain!! **

[/quote]

I sent you a PM on this. (I would be interested in learning OOP - properly - for Release #3 but not this current Release.)

There is no reason why I can’t build a secure Uploading Form using Procedural Code.

Debbie

If you are just check for gif, jpg, or png, why not use the exif_imagetype function? Please note, I am responding to the first post in the thread regarding checking the mime types.

**MODS: “Go Advanced” still not working and “Reply with Quote” is spotty at best…

Because the same issues I am having now exist with exif_imagetype.

Debbie

Okay, I have isolated where my problem is at, but have no clue why it is behaving as it is?!

First, here is a snippet of my code…


	$tempFile = $_FILES['userPhoto']['tmp_name'];

	if (empty($errors)){
		echo 'VAR_DUMP OF: getImageSize($tempFile)';
		var_dump(getImageSize($tempFile));
				
		$imageDetails = getImageSize($tempFile);
		$width = $imageDetails[0];
		$height = $imageDetails[1];
		$imageType = $imageDetails['mime'];

Test Case #1: Upload a Word document

$Filename = MyDocument.doc

$tempFile = /Applications/MAMP/tmp/php/phpQo64dh
VAR_DUMP OF: getImageSize($tempFile)

[B]boolean false
[/B]
[B][COLOR="#FF0000"]$imageDetails = ""
[/COLOR][/B]
$width =

$height =

$imageType = 

If I am uploading a Word Doc, then the function getImageSize() should return a FALSE which var_dump() is confirming. But why then is my variable $imageDetails an Empty String or Null??

Ironically, the logic of my code still works and I get a response of “Only Images can be uploaded (i.e. GIF, JPG, or PNG)”, but my code is expecting to get a FALSE from getImageSize() when a non-Image is uploaded?!

Test Case #2: Upload “test.php.jpg” which contains…


<?php
	phpinfo();
?>

> 
$Filename = test.php.jpg

$tempFile = /Applications/MAMP/tmp/php/phpRa3t5q
VAR_DUMP OF: getImageSize($tempFile)

[b]boolean false

$imageDetails = ""[/b]

$width =

$height =

$imageType = 


[b]Again, why isn't $imageDetails equal to FALSE?[/b]


Test Case# 3: Upload "00.txt" which is a blank text file


> 
$Filename = 00.txt

$tempFile = /Applications/MAMP/tmp/php/phpmIEkbT
VAR_DUMP OF: getImageSize($tempFile)
[QUOTE]( ! ) Notice: getimagesize() [function.getimagesize]: Read error! in /Users/user1/Documents/DEV/++htdocs/05_Debbie/members/upload.php on line 89
Call Stack
#	Time	Memory	Function	Location
1	0.0009	76760	{main}( )	../upload.php:0
2	0.0020	83124	getimagesize ( )	../upload.php:89


boolean false



> ( ! ) Notice: getimagesize() [function.getimagesize]: Read error! in /Users/user1/Documents/DEV/++htdocs/05_Debbie/members/upload.php on line 91
Call Stack
#	Time	Memory	Function	Location
1	0.0009	76760	{main}( )	../upload.php:0
2	0.1268	83444	getimagesize ( )	../upload.php:91


$imageDetails = ""

$width =

$height =

$imageType = [/QUOTE]

The fucntion returns FALSE but $imageDeails is equal to an Empty String/Null PLUS I now have two errors?!

I am pulling my hair out at how strangely things are behaving and this is not an issue of Procedural vs OOP.

Any ideas?

Thanks,

Debbie

I took the time to rewrite that object version as a single procedure… It assumes you have a $errors global array (I think I saw you had that at some point)…

imageHandlingProcedural.php


<?php

function resizeImageUpload(
	$sourceFile,$destFileRoot,
	$maxWidth,$maxHeight,
	$destFormat=IMAGETYPE_JPEG,
	$compression=15
) {
	global $errors;

	$formats=array(
		IMAGETYPE_GIF  => 'imagecreatefromgif',
		IMAGETYPE_JPEG => 'imagecreatefromjpeg',
		IMAGETYPE_PNG  => 'imagecreatefrompng'
	);
	
	if (extension_loaded('gd') && function_exists('gd_info')) {
		if (
			file_exists($sourceFile) &&
			($imageData=@getimagesize($sourceFile))
		) {
			if (isset($formats[$imageData[2]])) {
				if ($sourceImage=$formats[$imageData[2]]($sourceFile)) {
					$sourceWidth=imagesx($sourceImage);
					$sourceHeight=imagesy($sourceImage);
					if ($sourceWidth>$maxWidth) {
						$resultHeight=floor($sourceHeight*$maxWidth/$sourceWidth);
						if ($resultHeight>$maxHeight) {
							$resultWidth=floor($sourceWidth*$maxHeight/$sourceHeight);
							$resultHeight=$maxHeight;
						} else $resultWidth=$maxWidth;
					} else if ($sourceHeight>$maxHeight) {
						$resultWidth=floor($sourceWidth*$maxHeight/$sourceHeight);
						$resultHeight=$maxHeight;
					} else { /* smaller than max, leave it alone! */
						$resultWidth=$sourceWidth;
						$resultHeight=$sourceHeight;
					}
					$resultImage=imagecreatetruecolor($resultWidth,$resultHeight);
					imagecopyresampled(
						$resultImage,$sourceImage,
						0,0,
						0,0,
						$resultWidth,$resultHeight,
						$sourceWidth,$sourceHeight
					);
					switch ($destFormat) {
						case IMAGETYPE_GIF:
							$writeOK=imagegif($resultImage,$destFileRoot.'.gif');
						break;
						case IMAGETYPE_PNG:
							$writeOK=imagepng(
								$resultImage,
								$destFileRoot.'.png',
								round($compression*0.9)
							);
						break;
						case IMAGETYPE_JPEG:
							$writeOK=imagejpeg(
								$resultImage,
								$destFileRoot.'.jpg',
								100-$compression
							);
						break;
						default:
							$errors[]='Unable to save, unsupported format';
							return false;
					}
					if (!$writeOK) $errors[]='Unable to save image file';
					return $writeOK;
				} else $errors[]='Error loading source image';
			} else $errors[]='Unsupported file format';
		} else $errors[]='Invalid file or file format';
	} else $errors[]='GD Image module not found, PHP cannot process images';
	return false;
}
	
?>

As per the other one, destFileRoot should lack an extension, as that’s set by the $destFormat var which uses the IMAGETYPE_ constants. destFormat and compression are optional, defaulting to 15% lossy jpeg. A simple demo might look something like this:


<?php

require_once('imageHandlingProcedural.php');

$errors=array();

if (resizeImageUpload('test2.png','images/new',160,244,IMAGETYPE_JPEG,15)) {
	echo '
		<h1>Image converted ok</h1>
		<p>There were no errors reported during conversion</p>
		<img src="images/new.jpg" alt="resulting image" />';
} else {
	echo '
			<h1>There were errors attempting to process the image.</h1>
			<ul class="errors">';
		foreach ($errors as $error) {
			echo '
				<li>',$error,'</li>';
		}
		echo '
			</ul>';
		return true;
	} // errorReport

?>

It’s from another thread (I think, they’re getting blurred as this is all interconnected) your problem with things like image.php.jpg actually running (which I’ve NEVER seen apache do) sounds like a poorly configured server. If the server you’re working with was set up poorly, no amount of php code is going to make up for GAPING holes in it’s handling of file types. That’s when you call out whoever made the server and tell them “FIX THE BLASTED THING” or go somewhere else for hosting; as that’s unforgivably stupid on their part. Wasting time coding around an insecure server on your end is an exercise in futility.

Oh, and this thread works flawlessly if you turn off javascript – scripting on it’s still pretty much fubar. (I’m so shocked…)

Why not try this:

function isValidImgType( $file ) {
	return in_array( 
		exif_imagetype($file), 
		array(1,2,3)
	);
}

if(!isValidImgType('Img.png')) {
	echo 'Img.png is not a valid image!'; // Will not echo
} 
if(!isValidImgType('test.html')) {
	echo 'test.html is not a valid image!'; // Will echo 
} 			

Just replied via PM to her, but thought I’d share it in this thread should anyone else have this problem… something she said in the PM caught my eye:

When I select “test.php.jpg” the Manual says it should return FALSE and yet I get either a NULL or EMPTY STRING and that is what is throwing everything off…

AHA! My brain starts firing again. Null, zero or an empty string == false, but don’t === false… is that where she’s getting confused?

Then I thought to my use of

if ($imageData=@getimagesize($sourceFile)) {

vs. her

$imageData=@getimagesize($sourceFile);
$width=$imageData[0];
$height=$imageData[1];
if ($width && $height) {

If I remember correctly, mine will treat an empty string or null as a false condition, hers will not. I knew there was another reason for intercepting the result that way. The difference between == and ===.

proof tables man, proof tables…

(null == false) returns true
(0 == false) returns true
(‘’ == false) returns true
(undefined == false) returns true
(false == false) returns true

(null === false) returns false
(0 === false) returns false
(‘’ === false) returns false
(undefined === false) returns false
(false === false) returns true

Operating on the value like it’s an array bypasses actually checking for false, so in the case of false her latter calls to it (which should throw an error but PHP is a retard) are not going to throw errors or intercept the error properly.

In fact, I believe the getimagesize function actually returns an empty array as it’s result, not null or empty string (probably why your array indexes aren’t even throwing warnings)… and an empty array also == false but does not ===false…

DeathShadow,

What is happening in my Test Case #3 above?

Why the “Read Error!” ??


And why is var_dump() returning FALSE for files that are not images and yet this…

$imageDetails = getImageSize($tempFile);

…returns…

$imageDetails = “”

Debbie

probably the result is because it’s a valid file, but is NOT an image, so you get a empty string… (though I suspect that’s actually an empty array – in PHP the line between them is a bit blurred).

Though you are trying to run a var_dump on something that isn’t a variable… hence the massive error. You can’t var dump a function… and by the time you assign it to a variable, it’s likely too late to test for it… all those later values are operations on an element that’s undefined – and again if PHP’s error handling was worth a flying fig it should be throwing right there. You’re performing operations on a empty result set – a false condition, one of boolean false, numeric 0, an empty string or an empty array – OF COURSE all those are returning empty as well.

Try running your test cases against this code:


$tempFile = $_FILES['userPhoto']['tmp_name'];

if ($imageData=getimagesize($tempfile)) {
	echo '<pre>',print_r($imageData),'</pre>';
} else {
	echo 'is not an image';
}

You’re in for a surprise there, since if it returns “” that’s a false condition. If it returns an empty array it’s a false condition… That should accurately detect if it’s a image or not. Even so if you look at the code I provided I check for error results at EVERY step as part of making sure that “yes the input is an image” – and why doing the resize inline makes sure that whatever is output is actually an image. Making sure you write out an image format means that whatever they upload isn’t blindly copied to a directory that even has HTTP access in the first place.

Also… it’s getimagesize, not getImageSize – php is very inconsistent on that and is technically a case sensitive language… so stick with the name EXACTLY as it’s listed on php.net

The more I think on it, this is really where I think you’re failing to grasp booleans and PHP’s lack of typecasting.

The var_dump is failing, hence the massive error and why it’s returning a boolean false. IT didn’t run, there was an error with var_dump.

The latter one might be returning an empty string, but an empty string, empty array, 0, or null ALL == false – and they do not === false… which is why you should be doing the if statement on the ASSIGNMENT so that you don’t even TRY to use $imageData if the result is false… That’s where most of your issues lie, is you are assigning it, then trying to operate on it without ever testing it… TEST FIRST, if false, you have NO BUSINESS trying to use the result!

As I’ve said several times here:


   $width = $imageDetails[0];
        $height = $imageDetails[1];
        $imageType = $imageDetails['mime']; 

SHOULD NOT EVEN BE ATTEMPTED if $imageDetals=getimagesize($filename) returns false… which is why you test that FIRST before trying to do ILLEGAL variable accesses.

Basically:


if ($imageDetails=getimagesize($filename)) {
	// do whatever you want/need to do with imageDetails here
} else {
	// false condition, you have NO business trying to use imagedetails for ANYTHING
	// BECAUSE IT FAILED!
}

You aren’t trapping it that way, and that’s why it’s not working for you.

Also notice in my version I don’t even TRY to use the width/height returned by it and am only using it to detect the file format – I don’t grab the width/height for processing until AFTER I’ve loaded it.

You most certainly can do this…


	$tempFile = $_FILES['userPhoto']['tmp_name'];
	var_dump(getImageSize($tempFile));

…because it is working.

You’re performing operations on a empty result set – a false condition, one of boolean false, numeric 0, an empty string or an empty array – OF COURSE all those are returning empty as well.

Look, I agree with your running…

getimagesize($tempFile)

…before I check the array contents. Although I personally do not like your putting an assignment statement in the conditional like this…

		if ($imageDetails = getimagesize($tempFile)){

(NetBeans seems to agree with me!)

I didn’t disagree with your comments on this last night, however, since SitePoint crashed last night I didn’t get a chance to address that issue.

However, all of this is immaterial to the errors I am getting. Whether I use the code I had last night or your version, I have the same outstanding issue…

Try running your test cases against this code:


$tempFile = $_FILES['userPhoto']['tmp_name'];

if ($imageData=getimagesize($tempfile)) {
	echo '<pre>',print_r($imageData),'</pre>';
} else {
	echo 'is not an image';
}

Again, the print_r() behaves the same way as the dump_var(), and in fact if I echo my array values like this…


		$width = $imageDetails[0];
		$height = $imageDetails[1];
		$imageType = $imageDetails['mime'];

		echo '<p>$imageDetails = "' . $imageDetails . '"</p>';
		echo '<p>$width = ' . $width . '</p>';
		echo '<p>$height = ' . $height . '</p>';
		echo '<p>$imageType = ' . $imageType . '</p>';

…all three yield the same results.

You’re in for a surprise there, since if it returns “” that’s a false condition. If it returns an empty array it’s a false condition… That should accurately detect if it’s a image or not.

I will give you that var_dump() returns FALSE but the condition…


$imageDetails = getimagesize($tempFile)

…returns “”

Bottom line is this…

When I upload the file “00.txt” which is a blank text file, I get this error…

Notice: getimagesize() [function.getimagesize]: Read error! in /Users/user1/Documents/DEV/++htdocs/05_Debbie/members/upload.php on line 86
Call Stack
#	Time	Memory	Function	Location
1	0.0008	75200	{main}( )	../upload.php:0
2	0.0020	81396	getimagesize ( )	../upload.php:86

It is NOT caused by var_dump() or print_r().

But, obviously, getimagesize() does not like it?!

By contrast, if I upload…

MyDocument.doc
MySpreadsheet.xls
test.php.jpg
test2.php.jpg

…then they all come back as “Image not found” but I don’t get the Error.

(This is why Iadded the ampersand @ because this stupid “Notification” was breaking my code…)

Not sure if that helps?!

Debbie