note 117554 added to book.http
| From: | anton at example dot com | Date: | Sun, 28 Jun 2015 06:43:01 +0000 |
| Subject: | note 117554 added to book.http | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202984@lists.php.net to get a copy of this message | ||
For all those who still have code using the old pecl_http1 API and want to use PHP 5.6, you may want
to make a wrapper on top of pecl_http2.
The following code will work with PHP 5.6 if you use a wrapper:
<?php
$r = new HttpRequest($post_url, HttpRequest::METH_POST);
$r->setHeaders(array('User-Agent' => $user_agent));
$r->addPostFields($post_data);
try {
$r->send();
if ($r->getResponseCode() == 200) {
echo $r->getResponseBody();
}
} catch (HttpException $ex) {
// catch exception
}
?>
Here is the code of the wrapper of HttpRequst on top of pecl_http2 with PHP 5.6:
<?php
class HttpRequest {
private $url;
private $method;
private $headers;
private $post_fields;
private $http2_request;
private $http2_client;
private $http2_response;
const METH_POST = 'POST';
const METH_GET = 'GET';
function __construct($url, $method) {
$this->url = $url;
$this->method = $method;
$this->headers = array();
$this->post_fields = null;
}
function setHeaders($headers) {
$this->headers = $headers;
}
function addPostFields($post_fields) {
$this->post_fields = $post_fields;
}
function send() {
$this->http2_request = new http\Client\Request($this->method, $this->url,
$this->headers);
if ($this->method == HttpRequest::METH_POST && $this->post_fields) {
$this->http2_request->getBody()->append(new http\QueryString($this->post_fields));
}
$this->http2_client = new http\Client;
$this->http2_client->enqueue($this->http2_request)->send();
}
function getResponseCode() {
if (!$this->http2_response) $this->http2_response =
$this->http2_client->getResponse($this->http2_request);
return $this->http2_response->getResponseCode();
}
function getResponseBody() {
if (!$this->http2_response) $this->http2_response =
$this->http2_client->getResponse($this->http2_request);
return $this->http2_response->getBody();
}
}
?>
Feel free to extend and share your thoughts in order to get even more functionality of HttpRequest
work with PHP 5.6
----
Server IP: 72.52.91.14
Probable Submitter: 93.152.130.212
----
Manual Page -- http://php.net/manual/en/book.http.php
Edit -- https://master.php.net/note/edit/117554
Del: integrated -- https://master.php.net/note/delete/117554/integrated
Del: useless -- https://master.php.net/note/delete/117554/useless
Del: bad code -- https://master.php.net/note/delete/117554/bad+code
Del: spam -- https://master.php.net/note/delete/117554/spam
Del: non-english -- https://master.php.net/note/delete/117554/non-english
Del: in docs -- https://master.php.net/note/delete/117554/in+docs
Del: other reasons-- https://master.php.net/note/delete/117554
Reject -- https://master.php.net/note/reject/117554
Search -- https://master.php.net/manage/user-notes.php