note 102885 added to book.curl
| From: | frank at interactinet dot com | Date: | Sat, 12 Mar 2011 05:29:24 +0000 |
| Subject: | note 102885 added to book.curl | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-177816@lists.php.net to get a copy of this message | ||
I wrote the following to see if a submitted URL has a valid http response code and also if it
responds quickly.
Use the code like this:
<?php
$is_ok = http_response($url); // returns true only if http response code < 400
?>
The second argument is optional, and it allows you to check for a specific response code
<?php
http_response($url,'400'); // returns true if http status is 400
?>
The third allows you to specify how long you are willing to wait for a response.
<?php
http_response($url,'200',3); // returns true if the response takes less than 3 seconds and
the response code is 200
?>
<?php
function http_response($url, $status = null, $wait = null)
{
if(is_numeric($wait))
{
$time = microtime(true);
$expire = $time + $wait;
}
// we fork the process so we don't have to wait for a timeout
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if(!$head)
{
return FALSE;
}
if($status === null)
{
if($httpCode < 400)
{
return TRUE;
}
else
{
return FALSE;
}
}
elseif($status == $httpCode)
{
return TRUE;
}
return FALSE;
pcntl_wait($status); //Protect against Zombie children
} else {
// we are the child
if(
while(microtime(true) < $expire)
{
sleep(0.5);
}
return FALSE;
}
}
?>
Hope this example helps. It is not 100% tested, so any feedback is appreciated.
----
Server IP: 69.147.83.197
Probable Submitter: 99.248.36.139
----
Manual Page -- http://www.php.net/manual/en/book.curl.php
Edit -- https://master.php.net/note/edit/102885
Del: integrated -- https://master.php.net/note/delete/102885/integrated
Del: useless -- https://master.php.net/note/delete/102885/useless
Del: bad code -- https://master.php.net/note/delete/102885/bad+code
Del: spam -- https://master.php.net/note/delete/102885/spam
Del: non-english -- https://master.php.net/note/delete/102885/non-english
Del: in docs -- https://master.php.net/note/delete/102885/in+docs
Del: other reasons-- https://master.php.net/note/delete/102885
Reject -- https://master.php.net/note/reject/102885
Search -- https://master.php.net/manage/user-notes.php