SitePoint Sponsor

User Tag List

Page 2 of 2 FirstFirst 12
Results 26 to 47 of 47
  1. #26
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    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.

  2. #27
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    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
    Code:
    <?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:

    Code:
    <?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

  3. #28
    Foozle Reducer ServerStorm's Avatar
    Join Date
    Feb 2005
    Location
    Burlington, Canada
    Posts
    2,699
    Mentioned
    89 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    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
    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->setImageProperties( $img_data) 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
    ictus==""

  4. #29
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    ** 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

  5. #30
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    ** MODS: I can't quote anyone which makes responding to people a real manual pain!! **

    Quote Originally Posted by DoubleDee
    I appreciate your well-thought-out solution above, but you made the assumption I know OOP...

    Quote Originally Posted by deathshadow
    Might be time to give a good hard look at learning it
    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

  6. #31
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    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.

  7. #32
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    **MODS: "Go Advanced" still not working and "Reply with Quote" is spotty at best...


    Quote Originally Posted by centered effect View Post
    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.
    Because the same issues I am having now exist with exif_imagetype.


    Debbie

  8. #33
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    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...
    PHP 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)

    boolean false

    $imageDetails = ""

    $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...
    Code:
    <?php
    	phpinfo();
    ?>
    $Filename = test.php.jpg

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

    boolean false

    $imageDetails = ""


    $width =

    $height =

    $imageType =
    Again, why isn't $imageDetails equal to FALSE?


    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)
    ( ! ) 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 =
    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

  9. #34
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    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
    Code:
    <?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:

    Code:
    <?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...)

  10. #35
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    **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
    Why not try this:
    Code:
    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 
    }

  11. #36
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    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...

  12. #37
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    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...
    PHP Code:
    $imageDetails getImageSize($tempFile); 
    ...returns...
    $imageDetails = ""

    Debbie

  13. #38
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    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:
    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

  14. #39
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    And why is var_dump() returning FALSE for files that are not images and yet this...
    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:

    Code:
       $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:
    Code:
    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.

  15. #40
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by deathshadow60 View Post
    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...
    You most certainly can do this...
    PHP Code:
        $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...
    PHP Code:
    getimagesize($tempFile
    ...before I check the array contents. Although I personally do not like your putting an assignment statement in the conditional like this...
    PHP Code:
            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:
    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...
    PHP Code:
            $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...
    PHP Code:
    $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

  16. #41
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by deathshadow60 View Post
    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.
    var_dump() is NOT failing!

    Look at this snippet...
    PHP Code:
        $tempFile $_FILES['userPhoto']['tmp_name'];

        if (empty(
    $errors)){
            echo 
    'VAR_DUMP OF: getImageSize($tempFile)';
            
    var_dump(getImageSize($tempFile));
    exit(); 
    Results in this *successful* output...
    $Filename = MySpreadsheet.xls

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

    boolean false
    What is causing the Error (Technically it is a "Notification") is this line of code...
    PHP Code:
        if ($imageDetails getimagesize($tempFile)){ 
    But only when I try to upload my empty file called "00.txt"


    Still doubt me? Look...
    PHP Code:
        $tempFile $_FILES['userPhoto']['tmp_name'];

        if (empty(
    $errors)){

    //        echo 'VAR_DUMP OF: getImageSize($tempFile)';
    //        var_dump(getImageSize($tempFile));
    //        exit();

            
    if ($imageDetails getimagesize($tempFile)){ 
    When I try and upload "MySpreadsheet.xls" I get this...
    is not an image

    And when I try and upload "00.txt" I still get...
    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.0009 75000 {main}( ) ../upload.php:0
    2 0.0020 81196 getimagesize ( ) ../upload.php:86

    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!
    I get what you are saying, but I changed my code and that isn't the issue...


    As I've said several times here:

    Code:
       $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.
    It has been fixed...



    Basically:
    Code:
    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!
    }
    I didn't fix my code last night because of SitePoint freaking out...


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

    So to re-cap, the $10,000 question is "Why doesn't getimagesize() return FALSE on the file 00.txt but does on other non-Image files??" And more so, how do I handle that annoying Notification that is causing all of the issues??



    Debbie

  17. #42
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Generally PHP Notices can be ignored.

    To do it, you need to modify the php.ini.

    error_reporting = E_ALL & ~E_NOTICE

    Also just want to say this thread appears to have blown up to the point that it's difficult to follow.

  18. #43
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by wonshikee View Post
    Generally PHP Notices can be ignored.

    To do it, you need to modify the php.ini.

    error_reporting = E_ALL & ~E_NOTICE
    I know that, but usually there is a way to change your code to get rid of the E_NOTICE (e.g. Undefined Index).

    If I add back my @ then that fixes things (as long as I don't have another error that I'd want to see during debugging)...


    Also just want to say this thread appears to have blown up to the point that it's difficult to follow.
    I agree.

    To many people jumped in and went down too many paths...

    All I know is that I am stuck on getimagesize()


    Debbie

  19. #44
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    I know that, but usually there is a way to change your code to get rid of the E_NOTICE (e.g. Undefined Index).

    If I add back my @ then that fixes things (as long as I don't have another error that I'd want to see during debugging)...




    I agree.

    To many people jumped in and went down too many paths...

    All I know is that I am stuck on getimagesize()


    Debbie
    You can also do it with

    ini_set('error_reporting', E_ALL & ~E_NOTICE);

    in your PHP if you only want it for this script.

  20. #45
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    I made a empty 00.txt and ... oh, I see... That's related to the same error as exif_imagetype I think, where anything smaller than three bytes bombs (wonder if getimagesize actually calls exif_imagetype or if they share some code?)...

    So... your original approach of supressing the error with @ and then using what I'm saying for checking for false early should handle that... or you could do a filesize check.

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

    since that still returns false on error, the error supression isn't that bad a thing -- unlike what you had where you weren't trapping the result and just started working with the values...

    Probably why mine reads:
    Code:
    		if (
    			file_exists($sourceFile) &&
    			($imageData=@getimagesize($sourceFile))
    		) {
    I'd be interested in hearing what you mean by "netbeans agrees" on using assignment inside a value check -- since usually I don't trust 'tools' to make those types of determinations and processing the result of an assignment is one of the REASONS for PHP functions to return a proper value OR false... Sounds like some C or Java programmer making their software ***** about things they don't understand...

    Well actually, that doesn't make sense either -- maybe it falls into the same category as these script babies nowadays who say similar things about using 'with'?

    But let's face it, my stance on letting "tools" tell you how to code is quite well documented at this point.

  21. #46
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,934
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by deathshadow60 View Post
    I made a empty 00.txt and ... oh, I see... That's related to the same error as exif_imagetype I think, where anything smaller than three bytes bombs (wonder if getimagesize actually calls exif_imagetype or if they share some code?)...
    It's funny, because I saw that a long time ago in the Manual, but didn't connect the dots. (I had added "XXXXX" to "00.txt" so I figured that was good enough, plus my "MyDocument.doc" was blank, although in retrospect, larger than 4K or whatever.)

    I just added in a few rows of "XXXXXXXXXXXXX" to my "00.txt" and problem solved?!

    Looks like I'll add in something like this for safety...
    PHP Code:
    if (filesize($tempFile)<4){
        echo 
    "File Size Too Small";
        exit();


    So... your original approach of supressing the error with @ and then using what I'm saying for checking for false early should handle that... or you could do a filesize check.
    If I do that then I could remove the @ as far as this point goes.



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

    since that still returns false on error, the error supression isn't that bad a thing -- unlike what you had where you weren't trapping the result and just started working with the values...
    True.


    Probably why mine reads:
    Code:
    		if (
    			file_exists($sourceFile) &&
    			($imageData=@getimagesize($sourceFile))
    		) {
    Except this isn't an issue of the file "existing", it was an issue of the file "size"!


    I'd be interested in hearing what you mean by "netbeans agrees" on using assignment inside a value check -- since usually I don't trust 'tools' to make those types of determinations and processing the result of an assignment is one of the REASONS for PHP functions to return a proper value OR false... Sounds like some C or Java programmer making their software ***** about things they don't understand...
    It has a yellow icon that says "Possible accidental assignment, assignments in conditions should be avoided" in the popup bubble.


    Well actually, that doesn't make sense either -- maybe it falls into the same category as these script babies nowadays who say similar things about using 'with'? But let's face it, my stance on letting "tools" tell you how to code is quite well documented at this point.
    I know.

    So anyways, it looks like I fixed this bug that brought me to a grinding halt for the last two days?!

    I'll consult what you and others have written as far as other code, but I hope to keep to my style this go around.

    Hopefully the tougher part is solved now?!

    Thanks for helping,


    Debbie

  22. #47
    Non-Member bronze trophy
    Join Date
    Nov 2009
    Location
    Keene, NH
    Posts
    3,760
    Mentioned
    23 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DoubleDee View Post
    Looks like I'll add in something like this for safety...
    PHP Code:
    if (filesize($tempFile)<4){
        echo 
    "File Size Too Small";
        exit();

    If I do that then I could remove the @ as far as this point goes.
    More I think on it the more I'd kill error reporting with @ and just use the 'false' trap to handle it being in error... because most of the time the condition should be true; at which point why run that check EVERY time. You don't add more code for a 'rare condition' that can already be handled by the existing function status.

    Quote Originally Posted by DoubleDee View Post
    Except this isn't an issue of the file "existing", it was an issue of the file "size"!
    I was referring to the presence of the @, not the file_exists...

    Quote Originally Posted by DoubleDee View Post
    It has a yellow icon that says "Possible accidental assignment, assignments in conditions should be avoided" in the popup bubble.
    Wow, that's really stupid -- throwing a warning on a legitimate construct and the ENTIRE REASON C syntax languages have a distinction between = and ==, because it thinks it's a typo. I guess there's a reason if stuck in one of those garbage type editors I turn that bekaptah gobbledegook off. Put this alongside that illegible color coding garbage... actually no, file this alongside idiocy like 'code completion' that usually results in me having to spend more time correcting what the editor THINKS I want... actually no... it's worse than any of that. That type of 'warning' makes me immediately think of clippy.

    Probably why I use a flat text editor and test in XAMPP.

    Quote Originally Posted by DoubleDee View Post
    So anyways, it looks like I fixed this bug that brought me to a grinding halt for the last two days?!
    Hopefully so. Take a good hard look at the procedural version I posted since basically it provides everything you've been asking about from accessing the file type using getimagesize, loading and resizing the image, providing security (since it saves a resized/resampled copy instead of just copying it, so you KNOW the resulting file is an image) -- it's all there.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •