Download the PHP package popphp/pop-http without Composer
On this page you can find all versions of the php package popphp/pop-http. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download popphp/pop-http
More information about popphp/pop-http
Files in popphp/pop-http
Package pop-http
Short Description Pop Http Component for Pop PHP Framework
License BSD-3-Clause
Homepage https://github.com/popphp/pop-http
Informations about the package pop-http
pop-http
- Overview
- Install
- Client
- Quickstart
- Auth
- Options
- Automatic Content Negotiation
- Requests
- Rendering Requests
- Responses
- Handlers
- Promises
- Wait
- Then
- Forwarding
- Nesting
- CLI Conversion
- Server
- Request Headers & Data
- Filters
- Redirects & Forwards
- Rendering Responses
- Uploads
Overview
pop-http
is the main HTTP component for the Pop PHP Framework. It provides a robust
set of features to manage the many aspects of HTTP connections. It provides functionality
for the following:
- HTTP Client Transactions
- Create and manage outbound HTTP client requests and their responses
- Full control over request & response headers and data
- Manage authorization
- Manage and parse different request & response data types
- Automatic content negotiation of response data, where possible
- Use the request handler of your choice: curl, stream or curl-multi (defaults to curl)
- Send sync or async requests
- Support for promises
- Render client requests out to a raw string
- 2-way client to curl CLI command conversions
- HTTP Server Transactions
- Manage inbound HTTP server requests, headers and data
- Create and manage outbound HTTP server responses, headers and data
- Automatic content negotiation of request data, where possible
- Render server responses out to a raw string
- Easily handle file uploads and apply server-side settings and restrictions
pop-http
is a component of the Pop PHP Framework.
Install
Install pop-http
using Composer.
composer require popphp/pop-http
Or, require it in your composer.json file
"require": {
"popphp/pop-http" : "^5.0.0"
}
Top
Client
At its core, the client object works with a request object, a handler object and a response object to successfully execute an HTTP request. The request object can have request data. Both the request and response objects can have headers and a body. The response object will have a response code and response message, along with other helper functions to determine if the request yielded a successful response or an error.
NOTE: The constructor of the Pop\Http\Client
class is flexible and can take any of the following
parameters in any order:
- A URI string
- A
Pop\Http\Client\Request
object (which contains the URI) - A
Pop\Http\Client\Response
object (not common, as the response object is typically auto-populated) - A
Pop\Http\Auth
object (to assist with authorization) - A handler object that is an instance of
Pop\Http\Client\Handler\HandlerInterface
- An
$options
array
Quickstart
The most basic way to wire up a simple GET
request would be:
which is also the equivalent to:
or
In the examples above, the $response
object returned is a full response object, complete with all of the headers,
data, messaging and content that comes with an HTTP response. If you want to simply access the pertinent content of
the response object, this method can be used:
That method will attempt to auto-negotiate using the Content-Type
header and give an appropriate data response
or object. For example, if the content type of the response was application/json
, then the data returned will
be a PHP array representation of that JSON data.
POST Example
A POST
request can be given some data in the $options
array to send along with the request:
which is also the equivalent to:
or
All of the standard HTTP request methods are accessible in the manner outlined above. For example:
Top
Auth
There is an auth header class to assist in wiring up different types of standard authorization headers:
- Basic
- Bearer Token
- API Key
- Digest
Basic
Bearer Token
API Key
Digest
Digest authorization can be complex and require a number of different parameters. This is a basic example:
The digest auth header can be created from a WWW-Authenticate
header provided by the initial server response:
Top
Options
The client object supports an $options
array to pass in general configuration details and data for the request.
Supported keys in the options array are:
base_uri
- the base URI for re-submitting many requests with the same client to different endpoints on the same domainmethod
- the request method (GET, POST, PUT, PATCH, DELETE, etc.)headers
- an array of request headersuser_agent
- the user agent stringquery
- an array of request query data - reserved for only a URL-encoded query stringdata
- an array of request data - can be any request datafiles
- an array of files on disk to be sent with the requesttype
- set the request type (URL-form, JSON, XML or multipart/form)Request::URLENCODED
(application/x-www-form-urlencoded
)Request::JSON
(application/json
)Request::XML
(application/xml
)Request::MULTIPART
(multipart/form-data
)
auto
- trigger automatic content negotiation and return the parsed content, if possible (boolean)async
- trigger an asynchronous request (boolean)verify_peer
- enforce or disallow verifying the host for SSL connections (boolean)allow_self_signed
- allow or disallow the use of self-signed certificates for SSL connections (boolean)force_custom_method
- for Curl only. Forces the use ofCURLOPT_CUSTOMREQUEST
(boolean)
Here is an example using a base_uri
:
Here is an example to send some JSON data:
Here is an example to send some files:
Top
Automatic Content Negotiation
In the above examples, the $response
returned is a full response object. If you want to get the actual response
content, as mentioned above, you would call:
There are three ways to attempt content negotiation automatically and return the parsed content:
-
If you would like to attempt to parse the response content as JSON, regardless of any
Content-Type
header value or absence thereof, you can call thejson()
method to obtain a PHP array representation of the data: -
Similarly, if you would prefer to have a
Collection
object populated with the data content returned, you can call thecollect()
method. Internally, this will attempt thejson()
method as well: - You can set the
auto
option to true, which is contingent on the server response having the correctContent-Type
header. This will return a PHP array representation of the data:
If you still need to access the full response object, you can access it by calling:
Top
Requests
You can have granular control over the configuration of the request object by interacting with it directly.
There are four ways to configure the request for four different common data types:
- JSON
- XML
- URL-encoded form
- Multipart form
or
Each way effectively sets the appropriate Content-Type
header and properly formats the data for that data type.
Top
Rendering Requests
Client requests can be rendered out to a raw string:
Which would produce a string like this:
Top
Responses
Upon sending a request, the response object is automatically created and populated with the content from the raw response.
The header and body entities of both requests and responses are actually objects that store all their pertinent data. To access the actual data content, you would have to use methods such as these:
As mentioned above, using the following method will get the parsed content based on Content-Type
:
There are a number of helper methods to determine the response's status:
Top
Handlers
You can choose to use a different handler with the client object. The available handlers are:
Pop\Http\Client\Handler\Curl
- uses the PHP curl extension (default)Pop\Http\Client\Handler\Stream
- uses PHP stream functionalityPop\Http\Client\Handler\CurlMulti
- reserved for multiple parallel/concurrent requests at the same time
You can inject the handler into the client's constructor:
or through the setHandler()
method:
And then you can interact with the handler using the getHandler()
method:
Top
Curl
The handlers allow you to further customize the request by interfacing with each respective handler's settings.
For Curl
, that mainly includes setting additional Curl options needed for the request. (Please Note: Many
of the required Curl options, such as CURLOPT_URL
and CURLOPT_HTTPHEADER
are automatically set based on
the initial configuration of the client and request objects.)
Top
Stream
For Stream
, that includes setting context options and parameters needed for the request. (Please Note:
Many of the required Stream context options, such as ['http']
, ['http']['method']
and ['http']['header']
are automatically set based on the initial configuration of the client and request objects.)
Top
Curl Multi-Handler
The Curl Multi-Handler is a special use-case handler that allows for multiple parallel/concurrent requests
to be made at the same time. Each request will get its own Client
object, which will be registered with
the multi-handler object. The simplest way to configure a multi-handler object would be:
or
From there, the multi-handler object can send the requests:
The $multiHandler->getAllResponses()
method will return an array of all the response objects returned
from each of the requests.
Here is a more verbose way to configure a multi-handler object:
Top
Promises
Promises allow you to stage asynchronous requests within the application. When you initialize a client object and call it asynchronously, it will return a promise object. There are few different ways to achieve this:
which is equivalent to:
or
or
The multi-handler supports asynchronous requests as well and will return a promise object:
Top
Wait
Once you have a promise object, the most basic way to interact with it is to call wait()
, which simply
triggers the request and waits until the request is finished before allowing the application to continue.
Upon completion, the promise will return a response object. Otherwise, it will throw an exception, so it
is best to wrap the call in a try/catch
block:
If you need something that degrades a little more gracefully and need to suppress the thrown exception,
you can pass false
as the $unwrap
parameter into the wait()
method to prevent the exception from
being thrown:
Top
Then
You can use the then()
method, along with catch()
and finally()
to assign callbacks to handle
each specific scenario:
then()
- on success callbackcatch()
- on failure callbackfinally()
- callback to run at the end no matter what the result is
Additionally, a cancel callback can be set with the setCancel()
method and will be triggered at any
time the promise is cancelled. Once the promise is configured, the resolve()
method needs to be called
to finish the request.
As a convenience for a simple then()
call, you can pass a $resolve
flag as true
to force the promise
to resolve without having to call the resolve()
method:
The catch()
and finally()
methods also have the same $resolve
force flag.
Top
Forwarding
You can chain multiple then()
method calls together, which is sometimes called "forwarding" a promise.
The return of the first then()
call needs to be another promise object.
Top
Nesting
Promises can be "nested" together as well, whereas one resolved promise creates and triggers another promise:
Automatic Content Negotiation
Promises generated by client objects set for automatic content negotiation will return the parsed response content instead of a full response object.
Top
CLI Conversions
The CLI conversion feature allows you to convert client request objects into valid curl
commands to be used on
the CLI. It also supports converting valid curl
commands into client request objects to be used in a PHP application.
Curl Command to Client Object
Client Object to Curl Command
Top
Server
The server object and its components provide convenient and robust functionality to manage inbound server requests and outbound responses. At its core, and like the client object, the server object is compromised of a request object and a response object. However, opposite to the client object, the server object's request is typically auto-populated from the incoming request headers and data, while the response object is available to be configured as required to produce and send a response to the calling client.
Within an application, creating a server object will automatically take in the global request data that would come in from an inbound client request. This includes:
- Request data (
$_GET
,$_POST
, etc) - Request headers
- Request body
Top
Request Headers & Data
Headers
Body
Method
Data
If there is general data that has been parsed or raw data, that can be accessed via:
As an example, this curl
command pointing at the following URL with a PHP script can be executed:
with the contents of post.php
being:
Automatically, the server object's request object will be populated with the incoming request data. The example script above will produce:
From an incoming request, you can populate an appropriate response:
which will produce:
By default, the server object constructor will instantiate new request and response objects, but you can inject your own:
`
Top
Filters
As an extra layer of protection, you can add filters to the request object to filter incoming data:
And with the following curl command with data that contains tags and a single quote:
the data will be filtered:
Top
Redirects & Forwards
You can redirect to another URL by calling the following method:
You can forward a client object's response as the server's response:
Top
Rendering Responses
Server responses can be rendered out to a raw string:
Which would produce a string like this:
Top
Uploads
Basic file upload
The above code creates the upload object, sets the upload path and sets the basic defaults, which includes a max file size of 10MBs, and an array of allowed common file types as well as an array of common disallowed file types.
File upload names and overwrites
By default, the file upload object will not overwrite a file of the same name. In the above
example, if $_FILES['file_upload']['name']
is set to 'my_document.docx' and that file
already exists in the upload path, it will be renamed to 'my_document_1.docx'.
If you want to enable file overwrites, you can simply do this:
Also, you can give the file a direct name on upload like this:
And if you need to check for a duplicate filename first, you can use the checkFilename
method. If the filename exists, it will append a '_1' to the end of the filename, or loop
through until it finds a number that doesn't exist yet (_#). If the filename doesn't
exist yet, it returns the original name.
Top
All versions of pop-http with dependencies
popphp/pop-filter Version ^4.0.2
popphp/pop-mime Version ^2.0.1
popphp/pop-utils Version ^2.1.3
ext-curl Version *