note 76420 deleted from function.file-exists by cmb
| From: | cmb@php.net | Date: | Sun, 29 Sep 2019 07:10:55 +0000 |
| Subject: | note 76420 deleted from function.file-exists by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212372@lists.php.net to get a copy of this message | ||
Note Submitter: pcdinh at phpvietnam dot net
----
In response to havran at gmail dot com
Your function url_exists() does not work because it has got a big bug. curl_init does not make a
connection to that url until curl_exec() is executed. The return value from curl_init() shows if a
curl session can be started.
That function can be rewritten as follows
<?php
class Url
{
/**
* Check if an url is existed
*
* @param string $url
* @access static
* @return bool True if the url is accessible and false if the url is unaccessible or does not
exist
* @throws Exception An exception will be thrown when Curl session fails to start
*/
public static function exists($url)
{
if (null === $url || '' === trim($url))
{
throw new Exception('The url to check must be a not empty string');
}
$handle = curl_init($url);
if (false === $handle)
{
throw new Exception('Fail to start Curl session');
}
curl_setopt($handle, CURLOPT_HEADER, false);
curl_setopt($handle, CURLOPT_NOBODY, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
// grab Url
$connectable = curl_exec($handle);
// close Curl resource, and free up system resources
curl_close($handle);
return $connectable;
}
}
?>
How to use:
<?php
try
{
if (Url::exists('http://phpvietnam.net'))
{
// Do something here
}
}
catch (Exception $ex)
{
// Do something here
}
?>