Url exists function to check remote url


/ Published in: PHP
Save to your folder(s)

If you have to test if a remote url is correct you can use CURL and get the headers returned by the http request. If you receive a 200 code, than it’s ok, else the url is not correct:


Copy this code and paste it in your HTML
  1. function url_exists($url) {
  2. $ch = @curl_init($url);
  3. @curl_setopt($ch, CURLOPT_HEADER, TRUE);
  4. @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  5. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
  6. @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  7. $status = array();
  8. preg_match('/HTTP\/.* ([0-9]+) .*/', @curl_exec($ch) , $status);
  9. return ($status[1] == 200);
  10. }

URL: http://www.barattalo.it/2010/01/06/test-if-a-remote-url-exists-with-php-and-curl/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.