Skip to content

Instantly share code, notes, and snippets.

@muratpurc
Created September 22, 2011 10:13
Show Gist options
  • Save muratpurc/1234472 to your computer and use it in GitHub Desktop.
Save muratpurc/1234472 to your computer and use it in GitHub Desktop.
PHP: Check the existance of an ressource/file/url on a host (Linkchecker)
/**
* Checks the existance of an ressource/file/url on a host (Linkchecker).
*
* Usage:
* <code>
* $url = 'http://www.google.de/?q=foobar';
* $opt = array('timeout' => 3);
* $result = mp_urlCheck($url, $opt);
* if ($result == false) {
* echo 'ERROR: Errornumber: ' . $opt['errno'] . ', Errormessage: ' . $opt['errstr'];
* } else {
* echo 'SUCCESS';
* }
* </code>
*
* @param string $url The URL to check
* @param array $options Additional options as follows:
* - $options['port'] int The port which will be used for the connection, default is 80
* - $options['timeout'] int Timeout in seconds for the connection, default is 30
*/
function mp_urlCheck($url, array &$options=array())
{
$comp = @parse_url($url);
if (!isset($comp['host'])) {
return false;
}
// variable to store result
$status = false;
// some variables
$host = $comp['host'];
$port = (isset($options['port']) && (int) $options['port'] > 0) ? $options['port'] : 80;
$timeout = (isset($options['timeout']) && (int) $options['timeout'] > 0) ? $options['timeout'] : 30;
$pathAndQuery = ($comp['path']) ? $comp['path'] : '/';
if ($comp['query']) {
$pathAndQuery = $pathAndQuery . '?' . $comp['query'];
}
if ($conn = fsockopen($host, $port, $errno, $errstr, $timeout)) {
fwrite($conn, 'HEAD ' . $pathAndQuery . " HTTP/1.0\r\nHost: $host\r\n\r\n");
$response = fgets($conn, 22);
$status = (stripos($response, '200 OK') !== false);
fclose($conn);
}
$options['errno'] = $errno;
$options['errstr'] = $errstr;
return $status;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment