note 76420 added to function.file-exists
| From: | pcdinh at phpvietnam dot net | Date: | Sat, 14 Jul 2007 14:03:57 +0000 |
| Subject: | note 76420 added to function.file-exists | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-128516@lists.php.net to get a copy of this message | ||
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
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 58.187.69.13
----
Manual Page -- http://www.php.net/manual/en/function.file-exists.php
Edit -- https://master.php.net/note/edit/76420
Del: integrated -- https://master.php.net/note/delete/76420/integrated
Del: useless -- https://master.php.net/note/delete/76420/useless
Del: bad code -- https://master.php.net/note/delete/76420/bad+code
Del: spam -- https://master.php.net/note/delete/76420/spam
Del: non-english -- https://master.php.net/note/delete/76420/non-english
Del: in docs -- https://master.php.net/note/delete/76420/in+docs
Del: other reasons-- https://master.php.net/note/delete/76420
Reject -- https://master.php.net/note/reject/76420
Search -- https://master.php.net/manage/user-notes.php