note 117554 deleted from book.http by sobak

From: Date: Sun, 04 Dec 2016 07:16:04 +0000
Subject: note 117554 deleted from book.http by sobak
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208029@lists.php.net to get a copy of this message
Note Submitter: anton at example dot com ---- 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

« previous php.notes (#208029) next »