4

How can I check that a remote URL has a valid image extension?

What I want to do is upload images via link using PHP

copy('http://website.com/image.jpg', '/upload/filename.jpeg');

Code works fine but i want to check whether entered url has a valid image extension.

It should be jpg, png or gif file. Love to see a example of how to do this.

Your help and time is highly appreciated.

Mr Griever
  • 4,014
  • 3
  • 23
  • 41
Jordyn
  • 1,133
  • 2
  • 13
  • 28

2 Answers2

5

I found the solution myself.

exif_imagetype($image_url);

which will output the mime type for validation.

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
Jordyn
  • 1,133
  • 2
  • 13
  • 28
4

You can use preg_match to compare the filename to the known list:

if (preg_match('/\.(jpeg|jpg|png|gif)$/i', $image_url)) {
    // Successful match!
} else {
    // Not an image file extension
}

This will match a string that ends in a '.jpeg', '.jpg', '.png', or '.gif', whether they're uppercase, lowercase, or mixed case.

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43