I have built myself a simple HTTP request object, very basic
class Request {
protected $hostname;
protected $port = 80;
protected $method = 'GET';
protected $uri = '/';
protected $headers = array();
protected $body;
protected $handle;
protected $response;
public function __construct() {
$cookies = null;
foreach (\Cookie::getAll() as $k => $v) {
$cookies .= urlencode($k) . '=' . urlencode($v) . '; ';
}
$this->setHeader('Cookie', substr($cookies, 0, -2));
}
public function setHostname($name, $ssl = false) {
if (filter_var(gethostbyname($name), FILTER_VALIDATE_IP)) {
$this->hostname = ($ssl ? 'ssl://' : null) . $name;
$this->setHeader('Host', $name);
return true;
}
return false;
}
public function setPort($port) {
if ($port >= 1 && $port <= 65535) {
$this->port = (int)$port;
return true;
}
return false;
}
public function setMethod($method) {
$methods = [
'GET' => true,
'POST' => true,
'PUT' => true,
'DELETE' => true
];
if (isset($methods[$method])) {
$this->method = strtoupper($method);
return true;
}
return false;
}
public function setUri($uri) {
$this->uri = $uri;
return true;
}
public function setHeader($key, $value) {
$this->headers[$key] = $value;
return true;
}
public function removeHeader($key) {
unset($this->headers[$key]);
return true;
}
public function setBody($body) {
$this->body = $body;
return true;
}
public function send($async = false, $timeout = 30) {
$errno = null;
$errstr = null;
$this->setHeader('Content-Length', strlen($this->body));
if($async){
$this->setHeader('Connection', 'Close');
}
$this->response = null;
$this->handle = fsockopen($this->hostname, $this->port, $errno, $errstr, $timeout);
if (!$this->handle) {
throw new \Exception($errstr, $errno);
}
$headers = null;
foreach ($this->headers as $key => $value) {
$headers .= $key . ': ' . $value . "
";
}
$request = "{$this->method} {$this->uri} HTTP/1.1
{$headers}
" . $this->body;
fwrite($this->handle, $request);
if ($async) {
fclose($this->handle);
return;
}
while (!feof($this->handle)) {
echo $this->response . ' dgd<br/><br/><br/>';
$this->response .= fgets($this->handle, 8192);
}
fclose($this->handle);
}
public function getResponse() {
return $this->response;
}
}
When I send an "asynchronous" there's no problems but when I try to get the response I get maximum execution time exceeded error. I added an echo into the response-reading loop to debug and it only runs once. What may the problem be?
$r = new \Request();
$r->setHostname('localhost');
$r->setUri('/test.php');
$r->send();
echo "<pre>" . print_r($r, true) . "</pre>";
test.php
echo 'Test complete.';
Response source of the initial request
dgd<br/><br/><br/><br />
<b>Fatal error</b>: Maximum execution time of 30 seconds exceeded in <b>....\Request.php</b> on line <b>98</b><br />
Where line 98 is
$this->response .= fgets($this->handle, 8192);