An complete PSR-7 Request/Response implementation, with Cookie, and Session management/middleware.
It's best to install using Composer.
composer require symplely/http
All Request
and Response
classes share a base MessageAbstract
class that provides methods for interacting with the headers and body of a message.
The following methods are available on all Request
and Response
objects:
Gets the HTTP protocol version as a string (e.g., "1.0" or "1.1").
Returns a new instance of the message with the given HTTP protocol version as a string (e.g., "1.0" or "1.1").
Returns an array of the headers tied to the message. The array keys are the header names and each value is an array of strings for that header.
Makes a case-insensitive comparison to see if the header name given exists in the headers of the message. Returns true
if found, false
if not.
Returns an array of strings for the values of the given case-insensitive header. If the header does not exist, it will return an empty array.
Returns a comma-separated string of all the values of the given case-insensitive header. If the header does not exist, it will return an empty string.
Returns a new instance of the message while replacing the given header with the value or values specified.
<?php
use Async\Http\ServerRequest;
$request = new ServerRequest(...);
$newRequest = $request->withHeader(
'Content-Type',
'text/html'
);
$newRequest = $request->withHeader(
'Accept',
['application/json', 'application/xml']
);
Returns a new instance of the message while adding the given header with the value or values specified. Very similar to withHeader()
, except it maintains all existing headers.
Returns a new instance of the message while completely removing the given header.
Gets the body of the message in a Psr\Http\Message\StreamInterface
format.
Returns a new instance of the message using the given body. The body must be an instance of Psr\Http\Message\StreamInterface
.
There are two types of requests: Request
and ServerRequest
. The Request
class is used for outgoing requests, e.g. you send a request to another server. The ServerRequest
class is used for incoming requests, e.g. someone makes a request to your website for you to process and respond to.
Unless you're building an HTTP client, you'll most likely only use the ServerRequest
. Both are included because this library is a complete PSR-7 implementation.
- Request (outgoing)
- ServerRequest (incoming)
The Request
class is used to build an outgoing, client-side request. Requests are considered immutable; all methods that change the state of the request return a new instance that contains the changes. The original request is always left unchanged.
The static Request::create
is the most consistent way to build a request.
<?php
use Async\Http\Request;
$request = Request::create('GET', '/some/path?foo=bar');
Alternatively, you can build the request manually.
<?php
use Async\Http\Request;
$method = 'GET';
$uri = 'http://example.com/';
$headers = ['Content-Type' => 'application/json'];
$body = '{"ping": "pong"}';
$protocolVersion = '1.1';
// All of the parameters are optional.
$request = new Request(
$method,
$uri,
$headers,
$body,
$protocolVersion
);
In addition to all of the methods inherited from MessageAbstract
, the following methods are available:
Gets the message's request target as it will be seen for clients. In most cases, this will be the origin-form of the URI, unless a specific value has been provided. For example, if you request "http://example.com/search?q=test" then this will contain "/search?q=test").
Returns a new instance with the message's request target, as given.
Gets the HTTP method of the request.
Returns a new instance with the message's HTTP method set as given. The method name should be uppercase, however it will not correct the capitalization for you.
Gets the URI of the request as a Psr\Http\Message\UriInterface
.
Returns a new instance with the message's URI set as given. It must be given a Psr\Http\Message\UriInterface
. If preserve host is set to true
, it will not change the hostname of the request unless there isn't one already set.
The ServerRequest
class extends Request
and is used to build an incoming, server-side request. Requests are considered immutable; all methods that change the state of the request return a new instance that contains the changes. The original request is always left unchanged.
The ServerRequestFactory
is the most consistent way to build a request, regardless of the framework being used. All PSR-17 implementations share this method signature.
<?php
use Async\Http\ServerRequestFactory;
use Psr\Http\Message\ServerRequestInterface;
$factory = new ServerRequestFactory();
/** @var ServerRequestInterface */
$request = $factory->createServerRequest('GET', '/some/path?foo=bar');
$request = $factory->createServerRequest('GET', '/some/path?foo=bar', $serverParams);
In addition to all of the methods inherited from Request
, the following methods are available:
Gets the server parameters for the request. Typically this is the contents of the $_SERVER
variable, but doesn't have to be.
Gets the cookie parameters for the request. The return structure matches the format of what $_COOKIE
provides.
Returns a new instance of the request with the updated cookie parameters. The $cookies
parameter must match the structure that $_COOKIE
provides.
Gets the query string parameters for the request. Typically this is the contents of the $_GET
variable, but doesn't have to be. It's also possible for the query parameters to be out of sync with the URI query parameters, as setting one does not automatically set the other.
Returns a new instance of the request with the updated query parameters. Updating the query parameters will not automatically update the URI of the request.
Gets an array of normalized file uploads where each node of the array is a Psr\Http\Message\UploadedFileInterface
.
Returns a new instance of the request with the given file tree. Each node of the array must be a Psr\Http\Message\UploadedFileInterface
.
<?php
use Async\Http\ServerRequest;
$request = new ServerRequest(...);
// A simple list.
$newRequest = $request->withUploadedFiles(
[
'fileA' => $fileA,
'fileB' => $fileB,
]
);
// A nested list.
$newRequest = $request->withUploadedFiles(
[
'images' => [
'small' => $fileA,
'large' => $fileB,
],
'foo' => [
'bar' => [
'baz' => $fileC,
],
],
]
);
Gets the parameters of the request body. If the request Content-Type is either application/x-www-form-urlencoded
or multipart/form-data
, and the request method is POST
, this method will return an array similar to $_POST
. For other methods, such as PUT
or PATCH
, it will only parse the body if the Content-Type is application/x-www-form-urlencoded
or application/json
and then return the resulting array.
Returns a new instance of the request with the given parsed body. It only accepts array
, object
, or null
values.
Gets all custom attributes associated with the request. Attributes are application-specific data added to a request and can be anything, such as routing data or authentication flags.
Gets the given attribute for the request. If the attribute is not set, the default value will be returned.
Returns a new instance of the request with the given attribute set.
<?php
use Async\Http\ServerRequest;
$request = new ServerRequest(...);
// If you have a route such as /product/{id}
// And a request for /product/123
// You can set the 'id' attribute to the product ID
$newRequest = $request->withAttribute('id', 123);
// Some controller for the route
$controller = function ($request) {
// Look up product data
$productId = $request->getAttribute('id');
$product = $someRepository->find($productId);
// Do something with $product
};
$controller($newRequest);
Returns a new instance of the request without the given attribute.
There are three response classes available, mainly for convenience, but they all extend Response
.
The Response
class is used to return data to the client, typically in the form of HTML.
The static Response::create
is the most consistent way to build a response.
<?php
use Async\Http\Response;
$response = new Response();
/** @var ResponseInterface */
$response = Response::create();
$response = Response::create(404);
$response = Response::create(404, 'Not Found');
Or you can build one manually.
<?php
use Async\Http\Response;
// Defaults to a 200 OK response.
$response = new Response('Hello, world!');
// Use a given status code.
$response = new Response(204);
// Send custom headers.
$response = new Response(
302,
'Goodbye, world!',
['Location' => '/bye-bye']
);
In addition to all of the methods inherited from MessageAbstract
, the following methods are available:
Can be used to get the HTTP status code of the response (e.g., 200
or 404
).
Can be used to get the associated text for the status code (e.g., OK
or Not Found
).
Allows you to set the status and, optionally, the reason phrase of the response and returns the changes in a new response object.
<?php
use Async\Http\Response;
$response = new Response(...);
$newResponse = $response->withStatus(204);
$newResponse = $response->withStatus(204, 'No Content');
The JsonResponse
is a convenience extension of the Response
class to make returning JSON data easier. It automatically encodes whatever data is given to it as JSON and sets the Content-Type
header to application/json
.
<?php
use Async\Http\JsonResponse;
// Defaults to a 200 OK response.
$response = new JsonResponse(['message' => 'Hello, world!']);
// Custom 404 response.
$response = new JsonResponse(
['error' => 'Page not found'],
404
);
// Include additional headers.
$response = new JsonResponse(
['error' => 'Invalid credentials'],
401,
['X-Auth' => 'Failed']
);
The RedirectResponse
is a convenience extension of the Response
class to make redirects easier. It automatically sets the Location
header and includes a link in the body for the URI being redirected to.
<?php
use Async\Http\RedirectResponse;
// Defaults to a 302 redirect.
$redirect = new RedirectResponse('/some/path');
// Use a given status code.
$redirect = new RedirectResponse('/some/path', 301);
// Send custom headers.
$redirect = new RedirectResponse(
'/some/path',
302,
['X-Message' => 'Bye-bye']
);
The UploadedFile
class attempts to fix issues with how PHP structures the $_FILES
global.
The static UploadedFile::create
is the most consistent way to build an UploadedFile
.
<?php
use Async\Http\UploadedFile;
$stream = ...;
$file = UploadedFile::create($stream);
$file = UploadedFile::create($stream, $size, $error, $clientFilename, $clientMediaType);
The following methods are available:
Gets a Psr\Http\Message\StreamInterface
representing the file upload.
Moves the file to the target path. Internally, this uses move_uploaded_file()
or rename()
, depending on whether it's called in a SAPI or non-SAPI environment.
Gets the size of the file.
Gets any error codes associated to the file. This will return one of the UPLOAD_ERR_*
constants.
Gets the filename sent by the client. The value of this should not be trusted, as it can easily be faked.
Gets the media type sent by the client. The value of this should not be trusted, as it can easily be faked.
Streams provide a standardized way of accessing streamable data, such as request/response bodies and file uploads. However, the might be useful in any other part of your code.
The static Stream::create
, Stream::createFromFile
, Stream::createFromResource
is the most consistent way to build a Stream
.
<?php
use Async\Http\Stream;
$stream = Stream::create('string of data');
$stream = Stream::createFromFile('/path/to/file', 'r');
$resource = fopen('/path/to/file', 'wb+');
$stream = Stream::createFromResource($resource);
Alternatively, you can build a Stream
manually:
<?php
use Async\Http\Stream;
$stream = new Stream('string of data');
$stream = new Stream($resource);
The following methods are available:
Closes the stream and any underlying resources.
Separates the underlying resource from the stream and returns it.
Get the size of the stream, if known.
Returns the current position of the file pointer.
Returns true if the stream is at the end of the stream.
Returns whether or not the stream is seekable.
Seek to a position in the stream. $whence
should be one of PHP' SEEK_*
constants.
Seek to the beginning of the stream.
Returns whether or not the stream is writable.
Write data to the stream.
Returns whether or not the stream is readable.
Read data from the stream.
Returns the remaining contents of the stream.
Get stream metadata as an associative array or retrieve a specific key. The keys returned are identical to the keys returned from PHP's stream_get_meta_data()
function.
The Uri
class makes working with URI values easier, as you can easily get or set only certain parts of the URI.
The static Uri::create
is the most consistent way to build a Uri
.
<?php
use Async\Http\Uri;
$uri = Uri::create('/some/path?foo=bar');
$uri = Uri::create('https://example.com/search?q=test');
Alternatively, you can build a Uri
manually:
<?php
use Async\Http\Uri;
$uri = new Uri('/some/path?foo=bar');
$uri = new Uri('https://example.com/search?q=test');
The following methods are available:
Retrieve the scheme component of the URI.
Retrieve the authority component of the URI. The authority syntax of the URI is [user-info@]host[:port]
.
Retrieve the user information component of the URI. The syntax is username[:password]
.
Retrieve the host component of the URI.
Retrieve the port component of the URI. If the port is a standard port (e.g., 80 for HTTP or 443 for HTTPS), this will return null
.
Retrieve the path component of the URI.
Retrieve the query string of the URI.
Retrieve the fragment component of the URI.
Returns a new instance with the specified scheme.
Returns a new instance with the specified user information.
Returns a new instance with the specified host.
Returns a new instance with the specified port.
Returns a new instance with the specified path.
Returns a new instance with the specified query.
Returns a new instance with the specified fragment.
Cookies handles two problems, managing Cookie
Request headers and managing Set-Cookie
Response headers. It does this by way of introducing a Cookies class to manage collections of Cookie instances and a SetCookies class to manage collections of SetCookie instances.
These classes are a merge and rework of repo dflydev-fig-cookies .
Instantiating these collections looks like this:
use Async\Http\Cookies;
use Async\Http\SetCookies;
// Get a collection representing the cookies in the `Cookie` headers
// of a PSR-7 Request.
$cookies = Cookies::fromRequest($request);
// Get a collection representing the cookies in the Set-Cookie headers
// of a PSR-7 Response
$setCookies = SetCookies::fromResponse($response);
After modifying these collections in some way, they are rendered into a PSR-7 Request or PSR-7 Response like this:
// Put the `Cookie` headers and add them to the headers of a
// PSR-7 Request.
$request = $cookies->intoHeader($request);
// Put the `Set-Cookie` headers and add them to the headers of a
// PSR-7 Response.
$response = $setCookies->intoHeader($response);
For a simple Cookie
instance, creation.
use Async\Http\Cookie;
// Parse Set-Cookie header(s) and create an instance of CookieInterface.
$cookie = (new Cookie())
->create('PHPSESS=1234567890; Domain=domain.tld; Expires=Wed, 21 Oct 2015 07:28:00 GMT; HttpOnly; Max-Age=86400; Path=/admin; Secure');
// After making changes you can just cast it to a RFC-6265 valid string as show below.
$header = (string) $cookie;
Like PSR-7 Messages, Cookie
, Cookies
, SetCookie
, and SetCookies
are all represented as immutable value objects and all mutations will
return new instances of the original with the requested changes.
While this style of design has many benefits it can become fairly verbose very quickly. In order to get around that, the following provides two facades in an attempt to help simply things and make the whole process less verbose.
The easiest way to start working with Cookies is by using the
RequestCookies
and ResponseCookies
classes. They are facades to the
primitive Cookies classes. Their jobs are to make common cookie related
tasks easier and less verbose than working with the primitive classes directly.
There is overhead on creating Cookies
and SetCookies
and rebuilding
requests and responses. Each of these methods will go through this
process so be wary of using too many of these calls in the same section of
code. In some cases it may be better to work with the primitive classes
directly rather than using the facades.
Requests include cookie information in the Cookie request header. The
cookies in this header are represented by the Cookie
class.
use Async\Http\Cookie;
$cookie = Cookie::make('theme', 'blue');
To easily work with request cookies, use the RequestCookies
facade.
The get
method will return a Cookie
instance. If no cookie by the specified
name exists, the returned Cookie
instance will have a null
value.
The optional third parameter to get
sets the value that should be used if a
cookie does not exist.
use Async\Http\RequestCookies;
$cookie = RequestCookies::get($request, 'theme');
$cookie = RequestCookies::get($request, 'theme', 'default-theme');
The set
method will either add a cookie or replace an existing cookie.
The Cookie
primitive is used as the second argument.
use Async\Http\RequestCookies;
$request = RequestCookies::set($request, Cookie::make('theme', 'blue'));
The modify
method allows for replacing the contents of a cookie based on the
current cookie with the specified name. The third argument is a callable
that
takes a Cookie
instance as its first argument and is expected to return a
Cookie
instance.
If no cookie by the specified name exists, a new Cookie
instance with a
null
value will be passed to the callable.
use Async\Http\RequestCookies;
$modify = function (Cookie $cookie) {
$value = $cookie->getValue();
// ... inspect current $value and determine if $value should
// change or if it can stay the same. in all cases, a cookie
// should be returned from this callback...
return $cookie->withValue($value);
}
$request = RequestCookies::modify($request, 'theme', $modify);
The remove
method removes a cookie if it exists.
use Async\Http\RequestCookies;
$request = RequestCookies::remove($request, 'theme');
Note that this does not cause the client to remove the cookie. Take a look at
ResponseCookies::expire
to do that.
Responses include cookie information in the Set-Cookie response header. The
cookies in these headers are represented by the SetCookie
class.
use Async\Http\SetCookie;
$setCookie = SetCookie::create('lu')
->withValue('Rg3vHJZnehYLjVg7qi3bZjzg')
->withExpires('Tue, 15-Jan-2013 21:47:38 GMT')
->withMaxAge(500)
->rememberForever()
->withPath('/')
->withDomain('.example.com')
->withSecure(true)
->withHttpOnly(true)
;
To easily work with response cookies, use the ResponseCookies
facade.
The get
method will return a SetCookie
instance. If no cookie by the
specified name exists, the returned SetCookie
instance will have a null
value.
The optional third parameter to get
sets the value that should be used if a
cookie does not exist.
use Async\Http\ResponseCookies;
$setCookie = ResponseCookies::get($response, 'theme');
$setCookie = ResponseCookies::get($response, 'theme', 'simple');
The set
method will either add a cookie or replace an existing cookie.
The SetCookie
primitive is used as the second argument.
use Async\Http\ResponseCookies;
$response = ResponseCookies::set($response, SetCookie::create('token')
->withValue('a9s87dfz978a9')
->withDomain('example.com')
->withPath('/firewall')
);
The modify
method allows for replacing the contents of a cookie based on the
current cookie with the specified name. The third argument is a callable
that
takes a SetCookie
instance as its first argument and is expected to return a
SetCookie
instance.
If no cookie by the specified name exists, a new SetCookie
instance with a
null
value will be passed to the callable.
use Async\Http\ResponseCookies;
$modify = function (SetCookie $setCookie) {
$value = $setCookie->getValue();
// ... inspect current $value and determine if $value should
// change or if it can stay the same. in all cases, a cookie
// should be returned from this callback...
return $setCookie
->withValue($newValue)
->withExpires($newExpires)
;
}
$response = ResponseCookies::modify($response, 'theme', $modify);
The remove
method removes a cookie from the response if it exists.
use Async\Http\ResponseCookies;
$response = ResponseCookies::remove($response, 'theme');
The expire
method sets a cookie with an expiry date in the far past. This
causes the client to remove the cookie.
use Async\Http\ResponseCookies;
$response = ResponseCookies::expire($response, 'session_cookie');
Normally, PHP will send out headers for you automatically when you call session_start()
. However, this means the headers are not being sent as part of the PSR-7 response object, and are thus outside your control. Sessions
puts them back under your control by placing the relevant headers in the PSR-7 response.
This class is a merge and rework of Session
, and SessionHeadersHandler
class in repo, Relay.Middleware, and sessionware
.
This manager provides a nice OOP API to access session related actions:
$session = new \Async\Http\Sessions($id, $cacheLimiter, $cacheExpire);
When instantiating, you can pass a cache limiter value as the second constructor parameter. The allowed values are 'nocache', 'public', 'private_no_cache', or 'private'. If you want no cache limiter header at all, pass an empty string ''. The default is 'nocache'.
You can also pass a cache expire value, in minutes, as the fourth constructor parameter. The default is 180 minutes.
Sessions::getSession($serverRequest)
get session instance from requestSessions::start($id)
restart the session with idSessions::toArray()
retrieve all of the session dataSessions::getId()
session identifier retrievalSessions::regenerate()
cryptographically secure session identifier regenerationSessions::has($item)
verify a variable is saved in sessionSessions::set($item, $val)
save a variable into sessionSessions::get($item, $default)
get a variable from sessionSessions::unset($item)
remove a variable from sessionSessions::clear()
remove all session variablesSessions::close()
close session saving its contents, will also auto update $_SESSION on script shutdown, or __destruct.Sessions::destroy()
destroy session and all its contents
Session Middleware
The same instance also comes with a middleware handler which you can use to automatically initialize session, and write session cookie to response.
$session = new Sessions();
/**
* Session is started, populated with default parameters and the response has session cookie header.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param RequestHandlerInterface|callable|null $next
*
* The callable should have something similar to this signature:
* function (ServerRequestInterface $request, ResponseInterface $response) : Response {
* // your code
* }
*/
$response = $session($request, $response, $next);
Never make use of PHP built-in
session_*
functions (Session object would end up not being in sync) or$_SESSION
global variable (changes will be ignored and overridden). Use Sessions object API instead
Sessions
implements IteratorAggregate
, ArrayAccess
, Countable
So, it will look very much like $_SESSION
.
Just replace the $_SESSION
occurrences in your app with instance of the object.
$session->abcd = 'efgh';
//or
$session['abcd'] = 'efgh';
//or
$session->set('abcd', 'efgh');
$abcd = $session->abc;
//or
$abcd = $session['abcd'];
//or
$abcd = $session->get('abcd');
unset($session->abc);
//or
unset($session['abcd']);
//or
$session->unset('abcd');
$session->clear();