Sep 092011
Sometimes its handy to know if a website is up or not from code. E.G In a list of websites you are managing. I put this function together to tell me if the site is online or not.
php | | copy code | | ? |
01 | function site_exists($url) { |
02 | if (!empty($url) && ($con = curl_init($url)) !== false) { //start the connection |
03 | //Setup connection operators |
04 | curl_setopt($con, CURLOPT_TIMEOUT, 10); |
05 | curl_setopt($con, CURLOPT_RETURNTRANSFER, true); |
06 | |
07 | if (($data = curl_exec($con)) !== false && ($code = curl_getinfo($con, CURLINFO_HTTP_CODE)) !== false) { |
08 | return true; |
09 | } |
10 | |
11 | curl_close(); |
12 | } |
13 | |
14 | return false; |
15 | } |
by changing line 8 to the below code you can get the http status code for a more detailed report.
8 return $code;
If you are checking a lot of website you may want to change line 4, the current setting tells cURL to wait 10 seconds before failing. However, normally 2-3 seconds is acceptable. If you are checking hundreds of website you may want to turn off (Not available in PHP safe mode) php maximum execution time with set_time_limit ( int $seconds ) or infact turn this on.