How to Get Image Size with PHP

I include this here because I had to look it up a couple times at first, so I thought it might be useful to others. Often there is a need or desire to display an image which might not always have a consistent size. For example, if you are displaying an image gallery and don't want to take the time to resize all of your images but still want to have code that validates, you need to come up with some way to display the correct size of the image in the <img> tag. PHP provides a nifty function, getimagesize() for this purpose, but the function was written before CSS became the standard, so while it provides HTML-valid code, it does not provide nicely packaged XHTML-valid code.

So, you have two options:

  1. Use the HTML code, life won't end! You can do this by doing the following:
    
    <?php
    $myimage = "http://your.site.com/full/path/to/image.jpg";
    $size = getimagesize($myimage);
    ?>
    
    
    then use the following in your HTML:
    
    <img src="/full/path/to/image.jpg" <?php echo $size[3]; ?> />
    
    
    which produces:
    
    <img src="/full/path/to/image.jpg" width="300" height="60" />
    
    
    where the width and height match those of your image.
  2. Use this nifty little function instead:
    
    <?php
    function imageSize($size) {
    	$width = $size[0];
    	$height = $size[1];
    	print 'style="width:' . $width . 'px;height:' . $height . 'px;"';
    }
    $myimage = "http://your.site.com/full/path/to/image.jpg";
    $size = getimagesize($myimage);
    <img src="/full/path/to/image.jpg" <?php imageSize($myimage); ?> />
    ?>
    
    
    which produces:
    
    <img src="/full/path/to/image.jpg" style="width:300px;height:60px;" />
    
    

Don't forget to add the required alt tags!