Saber: PHP Coroutine HTTP Client - Swoole Humanization Library

Saber

Intro

The PHP high-performance HTTP client for Swoole Humanized Component Library, based on Swoole native coroutine client, supports multiple styles of operation, provides high-performance solutions at the bottom, allows developers to focus on feature development, and emancipate from traditional synchronous blocking network libs.

  • Development based on Swoole Coroutine Client
  • User-friendly style, ajax.js/axios.js/requests.py users' gospel, also supports PSR style operation
  • Complete browser-level cookie management mechanism, perfect for crawler/API proxy applications
  • Request/response interceptors
  • Multiple requests concurrent, concurrent redirection optimization, automated multiplexing long connections
  • Automatic transcoding of response messages
  • HTTPS connection, CA certificate automation support
  • HTTP/Socks5 Proxy Support
  • Redirection control, automated long connection multiplexing
  • Automation Encode Request/Parse Response Data
  • Milliseconds timeout timer
  • Random UA Generator

Requirement

  • PHP71 or later
  • Swoole 2.1.2 or later
  • Swoole 4 is the best

Examples

All of Saber's static methods have a corresponding method in the instance. The static method is implemented by a default client instance.

Coroutine

Swoole implements coroutine scheduling at the bottom layer, and the business layer does not need to be aware of it. It needs to be used in event callback functions such as onRequet, onReceive, and onConnect, or wrapped using the go keyword (swoole.use_shortname is enabled by default).

go(function () {
    echo SaberGM::get('http://httpbin.org/get');
})

Easy Request

SaberGM::get('http://httpbin.org/get');
SaberGM::post('http://httpbin.org/post');
SaberGM::put('http://httpbin.org/put');
SaberGM::patch('http://httpbin.org/patch');
SaberGM::delete('http://httpbin.org/delete');

Create Instance

API proxy service applicable

$saber = Saber::create([
    'base_uri' => 'http://httpbin.org',
    'headers' => [
        'User-Agent' => null,
        'Accept-Language' => 'en,zh-CN;q=0.9,zh;q=0.8',
        'DNT' => '1'
    ],
]);
echo $saber->get('/get');
echo $saber->post('/post');
echo $saber->patch('/patch');
echo $saber->put('/put');
echo $saber->delete('/delete');

Create Session

Session instance will save cookies automatically, Its implementation is browser-level complete.

$session = Saber::session([
    'base_uri' => 'http://httpbin.org',
    'redirect' => 0
]);
$session->get('/cookies/set?foo=bar&k=v&apple=banana');
$session->get('/cookies/delete?k');
echo $session->get('/cookies')->body;

Multi Request

Note: A concurrent redirection optimization scheme is used here. Multiple redirects are always concurrent and do not degenerate into a single request for the queue.

$responses = SaberGM::requests([
    ['uri' => 'http://github.com/'],
    ['uri' => 'http://github.com/'],
    ['uri' => 'https://github.com/']
]);
echo "multi-requests [ {$responses->success_num} ok, {$responses->error_num} error ]:\n" ."consuming-time: {$responses->time}s\n";

// multi-requests [ 3 ok, 0 error ]:
// consuming-time: 0.79090881347656s
// Arguments alias make it easier.
$saber = Saber::create(['base_uri' => 'http://httpbin.org']);
echo $saber->requests([
    ['get','/get'],
    ['post','/post'],
    ['patch','/patch'],
    ['put','/put'],
    ['delete','/delete']
]);

HTTP Proxy

Support HTTP and Socks5

$uri = 'http://myip.ipip.net/';
echo SaberGM::get($uri, ['proxy' => 'http://127.0.0.1:1087'])->body;
echo SaberGM::get($uri, ['proxy' => 'socks5://127.0.0.1:1086'])->body;

PSR Style

$bufferStream = new BufferStream();
$bufferStream->write(json_encode(['foo' => 'bar']));
$response = SaberGM::psr()
    ->withMethod('POST')
    ->withUri(new Uri('http://httpbin.org/post?foo=bar'))
    ->withQueryParams(['foo' => 'option is higher-level than uri'])
    ->withHeader('content-type', ContentType::JSON)
    ->withBody($bufferStream)
    ->exec()->recv();
echo $response->getBody();

Install

The recommended way to install Saber is through Composer

composer require swlib/saber:dev-master

how to install composer?

# Install Composer
curl -sS https://getcomposer.org/installer | php
# Global install
mv composer.phar /usr/local/bin/composer

After installing, you need to require Composer's autoloader:

require 'vendor/autoload.php';

You can then later update Saber using composer:

composer update

Configuration parameter table

| splitting multiple selectable values

keytypeintroductionexampleremark
protocol_versionstring 1.1HTTP2 in the roadmap
base_uristring http://httpbin.orgWill merge with uri according to rfc3986
uristring http://httpbin.org/get | /get | getU can use absolute and relative paths
methodstring get | post | head | patch | put | deleteThe underlying layer is automatically converted to uppercase
headersarray ['DNT' => '1'] | ['accept' => ['text/html'], ['application/xml']]The field names are case-insensitive, but the original case rules at the time of setting are retained. Each underlying field value is automatically split into arrays according to PSR-7.
cookiesarray|string ['foo '=> 'bar'] | 'foo=bar; foz=baz'The underlying is automatically converted to a Cookies object and its domain is set to the current uri, with browser-level complete properties.
useragentstring  The default is macos platform chrome
redirectintmax-value5The default is 3, 0 is not redirected.
keep_alivebool true | falseThe default is true, the connection will be reused automatically when redirecting
content_typestring text/plain | Swlib\Http\ContentType::JSONdefault is application/x-www-form-urlencoded
dataarray | string 'foo=bar&dog=cat' | ['foo' => 'bar']Will automatically encode data based on content_type
beforecallable | arrayinterceptor before requestfunction(Request $request){}Specific reference to the interceptor section
aftercallable | arrayinterceptor after responsefunction(Response $response){}Ditto.
timeoutfloat 0.5Default 5s, support millisecond timeout
proxystring http://127.0.0.1:1087 | socks5://127.0.0.1:1087suport http and socks5
sslintenable ssl?0=disable 1=enable 2=autoauto default
cafilestringca file__DIR__ . '/cacert.pem' 
ssl_verify_peerboolVerify server certificatefalse | trueclose default
ssl_allow_self_signedboolAllow self-signed certificatestrue | falseallow default

Alias

keyalias
method0
uri1 | url
data2 | body
base_uribase_url
aftercallback
content_typecontent-type
cookiescookie
headersheader
redirectfollow
form_dataquery
useragentua

Download Details:

Author: swlib
Source Code: https://github.com/swlib/saber

License: Apache-2.0 license

#php 

What is GEEK

Buddha Community

Saber: PHP Coroutine HTTP Client - Swoole Humanization Library

Http-client: Async HTTP/1.1+2 Client for PHP Based on Amp

Http client

This package provides an asynchronous HTTP client for PHP based on Amp. Its API simplifies standards-compliant HTTP resource traversal and RESTful web service consumption without obscuring the underlying protocol. The library manually implements HTTP over TCP sockets; as such it has no dependency on ext/curl.

Features

Installation

This package can be installed as a Composer dependency.

composer require amphp/http-client

Additionally, you might want to install the nghttp2 library to take advantage of FFI to speed up and reduce the memory usage on PHP 7.4.

Documentation

Documentation is bundled within this repository in the docs directory.

Examples

More extensive code examples reside in the examples directory.

Versioning

amphp/http-client follows the semver semantic versioning specification like all other amphp packages.

Everything in an Internal namespace or marked as @internal is not public API and therefore not covered by BC guarantees.

4.x

Stable and recommended version.

3.x

Legacy version. Use amphp/artax as package name instead.

2.x

No longer maintained. Use amphp/artax as package name instead.

1.x

No longer maintained. Use amphp/artax as package name instead.

Security

If you discover any security related issues, please email me@kelunik.com instead of using the issue tracker.

Download Details:

Author: Amphp
Source Code: https://github.com/amphp/http-client 
License: MIT license

#php #http #client #async 

Saber: PHP Coroutine HTTP Client - Swoole Humanization Library

Saber

Intro

The PHP high-performance HTTP client for Swoole Humanized Component Library, based on Swoole native coroutine client, supports multiple styles of operation, provides high-performance solutions at the bottom, allows developers to focus on feature development, and emancipate from traditional synchronous blocking network libs.

  • Development based on Swoole Coroutine Client
  • User-friendly style, ajax.js/axios.js/requests.py users' gospel, also supports PSR style operation
  • Complete browser-level cookie management mechanism, perfect for crawler/API proxy applications
  • Request/response interceptors
  • Multiple requests concurrent, concurrent redirection optimization, automated multiplexing long connections
  • Automatic transcoding of response messages
  • HTTPS connection, CA certificate automation support
  • HTTP/Socks5 Proxy Support
  • Redirection control, automated long connection multiplexing
  • Automation Encode Request/Parse Response Data
  • Milliseconds timeout timer
  • Random UA Generator

Requirement

  • PHP71 or later
  • Swoole 2.1.2 or later
  • Swoole 4 is the best

Examples

All of Saber's static methods have a corresponding method in the instance. The static method is implemented by a default client instance.

Coroutine

Swoole implements coroutine scheduling at the bottom layer, and the business layer does not need to be aware of it. It needs to be used in event callback functions such as onRequet, onReceive, and onConnect, or wrapped using the go keyword (swoole.use_shortname is enabled by default).

go(function () {
    echo SaberGM::get('http://httpbin.org/get');
})

Easy Request

SaberGM::get('http://httpbin.org/get');
SaberGM::post('http://httpbin.org/post');
SaberGM::put('http://httpbin.org/put');
SaberGM::patch('http://httpbin.org/patch');
SaberGM::delete('http://httpbin.org/delete');

Create Instance

API proxy service applicable

$saber = Saber::create([
    'base_uri' => 'http://httpbin.org',
    'headers' => [
        'User-Agent' => null,
        'Accept-Language' => 'en,zh-CN;q=0.9,zh;q=0.8',
        'DNT' => '1'
    ],
]);
echo $saber->get('/get');
echo $saber->post('/post');
echo $saber->patch('/patch');
echo $saber->put('/put');
echo $saber->delete('/delete');

Create Session

Session instance will save cookies automatically, Its implementation is browser-level complete.

$session = Saber::session([
    'base_uri' => 'http://httpbin.org',
    'redirect' => 0
]);
$session->get('/cookies/set?foo=bar&k=v&apple=banana');
$session->get('/cookies/delete?k');
echo $session->get('/cookies')->body;

Multi Request

Note: A concurrent redirection optimization scheme is used here. Multiple redirects are always concurrent and do not degenerate into a single request for the queue.

$responses = SaberGM::requests([
    ['uri' => 'http://github.com/'],
    ['uri' => 'http://github.com/'],
    ['uri' => 'https://github.com/']
]);
echo "multi-requests [ {$responses->success_num} ok, {$responses->error_num} error ]:\n" ."consuming-time: {$responses->time}s\n";

// multi-requests [ 3 ok, 0 error ]:
// consuming-time: 0.79090881347656s
// Arguments alias make it easier.
$saber = Saber::create(['base_uri' => 'http://httpbin.org']);
echo $saber->requests([
    ['get','/get'],
    ['post','/post'],
    ['patch','/patch'],
    ['put','/put'],
    ['delete','/delete']
]);

HTTP Proxy

Support HTTP and Socks5

$uri = 'http://myip.ipip.net/';
echo SaberGM::get($uri, ['proxy' => 'http://127.0.0.1:1087'])->body;
echo SaberGM::get($uri, ['proxy' => 'socks5://127.0.0.1:1086'])->body;

PSR Style

$bufferStream = new BufferStream();
$bufferStream->write(json_encode(['foo' => 'bar']));
$response = SaberGM::psr()
    ->withMethod('POST')
    ->withUri(new Uri('http://httpbin.org/post?foo=bar'))
    ->withQueryParams(['foo' => 'option is higher-level than uri'])
    ->withHeader('content-type', ContentType::JSON)
    ->withBody($bufferStream)
    ->exec()->recv();
echo $response->getBody();

Install

The recommended way to install Saber is through Composer

composer require swlib/saber:dev-master

how to install composer?

# Install Composer
curl -sS https://getcomposer.org/installer | php
# Global install
mv composer.phar /usr/local/bin/composer

After installing, you need to require Composer's autoloader:

require 'vendor/autoload.php';

You can then later update Saber using composer:

composer update

Configuration parameter table

| splitting multiple selectable values

keytypeintroductionexampleremark
protocol_versionstring 1.1HTTP2 in the roadmap
base_uristring http://httpbin.orgWill merge with uri according to rfc3986
uristring http://httpbin.org/get | /get | getU can use absolute and relative paths
methodstring get | post | head | patch | put | deleteThe underlying layer is automatically converted to uppercase
headersarray ['DNT' => '1'] | ['accept' => ['text/html'], ['application/xml']]The field names are case-insensitive, but the original case rules at the time of setting are retained. Each underlying field value is automatically split into arrays according to PSR-7.
cookiesarray|string ['foo '=> 'bar'] | 'foo=bar; foz=baz'The underlying is automatically converted to a Cookies object and its domain is set to the current uri, with browser-level complete properties.
useragentstring  The default is macos platform chrome
redirectintmax-value5The default is 3, 0 is not redirected.
keep_alivebool true | falseThe default is true, the connection will be reused automatically when redirecting
content_typestring text/plain | Swlib\Http\ContentType::JSONdefault is application/x-www-form-urlencoded
dataarray | string 'foo=bar&dog=cat' | ['foo' => 'bar']Will automatically encode data based on content_type
beforecallable | arrayinterceptor before requestfunction(Request $request){}Specific reference to the interceptor section
aftercallable | arrayinterceptor after responsefunction(Response $response){}Ditto.
timeoutfloat 0.5Default 5s, support millisecond timeout
proxystring http://127.0.0.1:1087 | socks5://127.0.0.1:1087suport http and socks5
sslintenable ssl?0=disable 1=enable 2=autoauto default
cafilestringca file__DIR__ . '/cacert.pem' 
ssl_verify_peerboolVerify server certificatefalse | trueclose default
ssl_allow_self_signedboolAllow self-signed certificatestrue | falseallow default

Alias

keyalias
method0
uri1 | url
data2 | body
base_uribase_url
aftercallback
content_typecontent-type
cookiescookie
headersheader
redirectfollow
form_dataquery
useragentua

Download Details:

Author: swlib
Source Code: https://github.com/swlib/saber

License: Apache-2.0 license

#php 

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website?

HourlyDeveloper.io has always been an industry leader for companies and business owners looking to hire PHP web developer. By choosing to Hire PHP Developer from our company, you can always expect the best results. Our PHP services and solutions are always flexible which means that no matter the nature of your project, you can always count on us for getting the best PHP expertise.

Consult with our experts: https://bit.ly/3aEGxPy

#hire php developer #php developer #php development company #php development services #php development #php

Guzzle: An Extensible PHP HTTP Client

Guzzle, PHP HTTP client 

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

  • Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc...
  • Can send both synchronous and asynchronous requests using the same interface.
  • Uses PSR-7 interfaces for requests, responses, and streams. This allows you to utilize other PSR-7 compatible libraries with Guzzle.
  • Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients.
  • Abstracts away the underlying HTTP transport, allowing you to write environment and transport agnostic code; i.e., no hard dependency on cURL, PHP streams, sockets, or non-blocking event loops.
  • Middleware system allows you to augment and compose client behavior.
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();

Help and docs

We use GitHub issues only to discuss bugs and new features. For support please refer to:

Installing Guzzle

The recommended way to install Guzzle is through Composer.

composer require guzzlehttp/guzzle

Version Guidance

VersionStatusPackagistNamespaceRepoDocsPSR-7PHP Version
3.xEOLguzzle/guzzleGuzzle[v3][guzzle-3-repo][v3][guzzle-3-docs]No>= 5.3.3
4.xEOLguzzlehttp/guzzleGuzzleHttp[v4][guzzle-4-repo]N/ANo>= 5.4
5.xEOLguzzlehttp/guzzleGuzzleHttp[v5][guzzle-5-repo][v5][guzzle-5-docs]No>= 5.4
6.xSecurity fixesguzzlehttp/guzzleGuzzleHttp[v6][guzzle-6-repo][v6][guzzle-6-docs]Yes>= 5.5
7.xLatestguzzlehttp/guzzleGuzzleHttp[v7][guzzle-7-repo][v7][guzzle-7-docs]Yes>= 7.2

Security

If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see Security Policy for more information.

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Author: Guzzle
Source Code: https://github.com/guzzle/guzzle 
License: MIT License

#php #http #client 

Buzz: PHP's Lightweight HTTP Client

Buzz - Scripted HTTP browser 

Buzz is a lightweight (<1000 lines of code) PHP 7.1 library for issuing HTTP requests. The library includes three clients: FileGetContents, Curl and MultiCurl. The MultiCurl supports batch requests and HTTP2 server push.

Installation

Install by running:

composer require kriswallsmith/buzz

You do also need to install a PSR-17 request/response factory. Buzz uses that factory to create PSR-7 requests and responses. Install one from this list.

Example:

composer require nyholm/psr7

Usage

This page will just show you the basics, please read the full documentation.

use Buzz\Browser;
use Buzz\Client\FileGetContents;

$client = new FileGetContents(new Psr17ResponseFactory());
$browser = new Browser($client, new Psr17RequestFactory());
$response = $browser->get('https://www.google.com');

echo $browser->getLastRequest()."\n";
// $response is a PSR-7 object.
echo $response->getStatusCode();

You can also use the low-level HTTP classes directly.

use Buzz\Client\FileGetContents;

$request = new PSR7Request('GET', 'https://google.com/foo');

$client = new FileGetContents(new Psr17ResponseFactory());
$response = $client->sendRequest($request, ['timeout' => 4]);

echo $response->getStatusCode();

Note

The two new Psr17ResponseFactory() and new Psr17RequestFactory() are placeholders for whatever PSR-17 factory you choose. If you use nyholm/psr7 then the example above would start like:

use Buzz\Browser;
use Buzz\Client\FileGetContents;
use Nyholm\Psr7\Factory\Psr17Factory;

$client = new FileGetContents(new Psr17Factory());
$browser = new Browser($client, new Psr17Factory());
$response = $browser->get('https://www.google.com');

HTTP2 server push

Buzz MultiCurl client support HTTP2 server push.

use Buzz\Client\MultiCurl;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7\Request;

$client = new MultiCurl(new Psr17Factory());

$start = microtime(true);
$response = $client->sendRequest(new Request('GET', 'https://http2.golang.org/serverpush', [], null, '2.0'));
$timeFirstRequest = microtime(true) - $start;

// Parse response to find asset version. 
$body = $response->getBody()->__toString();
$id = null;
if (preg_match('#/serverpush/static/style.css\?([0-9]+)#sim', $body, $matches)) {
    $id = $matches[1];
}

// Make two new requests
$start = microtime(true);
$client->sendRequest(new Request('GET', 'https://http2.golang.org/serverpush/static/style.css?'.$id));
$client->sendRequest(new Request('GET', 'https://http2.golang.org/serverpush/static/playground.js?'.$id));
$timeOtherRequests = microtime(true) - $start;

echo 'First: '.$timeFirstRequest."\n";
echo 'Other: '.$timeOtherRequests."\n";

Since the two other requests was pushed, we spend no time fetching those.

First: 1.04281
Other: 0.00027

You can configure what request you want to accept as pushed with the push_function_callback option.

The Idea of Buzz

Buzz was created by Kris Wallsmith back in 2010. The project grown very popular over the years with more than 7 million downloads.

Since August 2017 Tobias Nyholm is maintaining this library. The idea of Buzz will still be the same, we should have a simple API and mimic browser behavior for easy testing. We should not reinvent the wheel and we should not be as powerful and flexible as other clients (ie Guzzle). We do, however, take performance very seriously.

We do love PSRs and this is a wish list of what PSR we would like to support:

  • PSR-1 (Code style)
  • PSR-2 (Code style)
  • PSR-4 (Auto loading)
  • PSR-7 (HTTP messages)
  • PSR-17 (HTTP factories)
  • PSR-18 (HTTP client)

The goal

Since the release of 1.0 Buzz has reached its goal of being a lightweight client that covers 90% of all use cases. There are no plans to actively develop new features or change the existing API. There are alternatives for people that wants an more actively maintained HTTP clients. One that is particularly popular and got a big community behind it is the
Symfony HTTP Client.

Contribute

Buzz is great because it is small, simple and yet flexible. We are always happy to receive bug reports and bug fixes. We are also looking forward to review a pull request with a new middleware, especially if the middleware covers a common use case.

We will probably not accept any configuration option or feature to any of the clients or the Browser.

Backwards Compatibility Promise

We take backwards compatibility very seriously as you should do with any open source project. We strictly follow Semver. Please note that Semver works a bit different prior version 1.0.0. Minor versions prior 1.0.0 are allow to break backwards compatibility.

Being greatly inspired by Symfony's bc promise, we have adopted their method of deprecating classes, interfaces and functions.

Running the tests

There are 2 kinds of tests for this library; unit tests and integration tests. They can be run separably by:

./vendor/bin/phpunit --testsuite Unit
./vendor/bin/phpunit --testsuite Integration

The integration tests makes real HTTP requests to a webserver. There are two different webservers used by our integration tests. A real Nginx server and PHP's built in webserver. The tests that runs with PHP's webserver are provided by php-http/client-integration-tests.

To start the server, open terminal A and run:

./vendor/bin/http_test_server

The other type of integration tests are using Nginx. We use Docker to start the Nginx server.

docker build -t buzz/tests .
docker run -d -p 127.0.0.1:8022:80 buzz/tests

You are now ready to run the integration tests

./vendor/bin/phpunit --testsuite Integration

Test Server Push

To use HTTP/2 server push you need to run the very latest PHP version. PHP also need to use cUrl > 7.61.1 and be compiled with libnghttp2. You can use docker:

composer update
docker run -it --rm --name php-latest -v  "$PWD":/usr/src/myapp -w /usr/src/myapp tommymuehle/docker-alpine-php-nightly \
  php vendor/bin/phpunit tests/Integration/MultiCurlServerPushTest.php

Author: Kriswallsmith
Source Code: https://github.com/kriswallsmith/Buzz 
License: MIT License

#php #http #client