php - Check if image exists on remote URL with or without http/https -


i'm trying check whether image exists or not on remote url.

what have far :

validator::extend('valid_img_url', function ($attribute, $value, $parameters, $validator) {     $handle = curl_init($value);     curl_setopt($handle,  curlopt_returntransfer, true);      $response = curl_exec($handle);     $httpcode = curl_getinfo($handle, curlinfo_http_code);     if($httpcode >= 200 && $httpcode <= 400) {        return getimagesize($value) !== false;        }  }); 

it works fine if given remote url example https://website.com. when given remote url website.com without http or https, got error getimagesize(website.com): failed open stream: no such file or directory.

how solve issue ? appreciated, thanks!

instead of checking accessibility , image size in 2 steps, combine in one:

validator::extend('valid_img_url', function ($attribute, $value, $parameters, $validator) {      $ch = curl_init($value);      curl_setopt($ch, curlopt_returntransfer, true);      curl_setopt($ch, curlopt_header, true);      curl_setopt($ch, curlopt_nobody, true);       $data = curl_exec($ch);      $size = curl_getinfo($ch, curlinfo_content_length_download);      $mime = curl_getinfo($ch, curlinfo_content_type);      curl_close($ch);      return $httpcode >= 200 && $httpcode <= 400 && $size > 0 && substr($mime, 0, 5) == 'image'); } 

to use power of getimagesize add piece of code:

validator::extend('valid_img_url', function ($attribute, $value, $parameters, $validator) {     $handle = curl_init($value);     curl_setopt($handle,  curlopt_returntransfer, true);      $response = curl_exec($handle);     $httpcode = curl_getinfo($handle, curlinfo_http_code);     if($httpcode >= 200 && $httpcode <= 400) {         if (!preg_match("~^(?:f|ht)tps?://~i", $value)) {             $value = "http://" . $value;         }        return getimagesize($value) !== false;        } }); 

it add missing http if there no one. remember if url accessible via https without redirect can throw error.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -