PHP Function getimagesize() Failing For Local Images
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.
0 comments:
Post a Comment