R
R
Roman Sokharev2014-05-05 16:26:31
PHP
Roman Sokharev, 2014-05-05 16:26:31

Is it possible to check if a linked document is an image?

I've been doing php for a year and a half. But this is the first time I've come across this issue. Is there an adequate way to check if a linked document is an image? So far, I can't think of anything better than getimagesize(). Is there a way to check headers?
What is the actual problem: there are links to images, but they are not quite direct - apparently, this is an API that returns an image if it exists, and gives an error page if it does not. I upload pictures using curl (I'm not a curl guru, I just dug up an example in the vastness of the Vast, and drank it "for myself")...

if(!file_exists('./images/'. $target_image){
                $ch = curl_init('http://site.com/images/' . $source_image);
                $fp = fopen('./images/'. $target_image);
                curl_setopt($ch, CURLOPT_FILE, $fp);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_close($ch);
                fclose($fp);
}

The problem is that some pictures are "non-pictures". In this case, complete crap is written to my image file, which is not a picture ... I'm not "what" just tell me the azimuth of the direction of the shovel when digging.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2014-05-05
@greabock

Option 1. check the mime-type given by the server when uploading a file.
Option 2. Try to load a picture through GD for example.

K
Konstantin Velichko, 2014-05-05
@Zoxon

getimagesize

4
404, 2014-05-05
@404

If this is an api and it returns the same page in case of an error (or almost the same), then I would check from the opposite - if the response is not an error page. There may be different solutions to this. In the ideal case, the api should not only return the error page, but also set the appropriate http response code. If the service returns 200 anyway, then you can parse the response body.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question