PHP Function getimagesize() Failing For Local Images

April 15th, 2014 - Posted by Steve Marks to PHP, Web Development.

When working with images in a PHP script, there might come a time when you need to use the getimagesize() function in order to discover more about the image. Whether you want to know the dimensions or the filetype, using this function can get you the information you require.

Earlier today I needed to use this function to obtain the width and height of a particular image. The image in question was hosted on the same server as the PHP script so I simply attempted to do the following:

list($width, $height, $type, $attr) = getimagesize('/images/my-image.jpg');

Unfortunately this just didn’t work. No information about the image was obtained, and all I got was an error.

If you’re familiar with the getimagesize() function you’ll know that it can support either a local or a remote path. As a result, I tried a remote path instead to see if this would work:

list($width, $height, $type, $attr) = getimagesize('http://mydomain.com/images/my-image.jpg');

Straight away this worked.

The only issue with using the remote path is that it’s slower. By using a full URL it makes a separate HTTP request and thus takes longer. This is something I wanted to avoid so I went back to referencing the image locally.

The Solution

After a bit of investigation and playing around, I figured that the path to the local image had to be relevant to the server’s root. As a result, a quick change to the following…

list($width, $height, $type, $attr) = getimagesize($_SERVER['DOCUMENT_ROOT'] . '/images/my-image.jpg');

… and it started to work immediately, providing me the image dimensions I was after.

Tags:
This entry was posted on Tuesday, April 15th, 2014 at 8:13 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first