HTTP Requests/Responses
Table of Contents
- Introduction
- Requests
- Collections
- Query String Data
- Post Data
- Request Data
- Put Data
- Patch Data
- Delete Data
- Cookies
- Server Data
- Header Data
- File Data
- Env Data
- Getting the Path
- Getting the Method
- Body
- AJAX
- Getting the Client IP Address
- Checking if HTTPS
- Getting the Full URL
- Getting the Previous URL
- Authentication Data
- Using Proxies
- Responses
Introduction
Opulence makes interacting with HTTP requests and responses easy. Tasks like checking if a POST variable is set before using it are repetitive when working directly with PHP's $_POST
global array. If you've ever worked with cookies and gotten the "headers already sent" error, you know how annoying it is to work with the HTTP tools PHP gives you by default. Use Opulence's tools, and stop worry about stuff like this.
Requests
Opulence has a wrapper around an HTTP request in the Opulence\Http\Requests\Request
class.
Collections
Superglobal request data, eg $_GET
and $_POST
are wrapped into Opulence\Http\Collection
objects, which have the following methods:
get($key)
has($key)
remove($key)
set($key, $value)
Query String Data
$request->getQuery()->get('foo');
Note: This is similar to the data in
$_GET
.getQuery()
returns aCollection
object.
Post Data
$request->getPost()->get('foo');
Note: This is similar to the data in
$_POST
.getPost()
returns aCollection
object.
Request Data
$request->getInput('foo');
Note: This is similar to the data in
$_REQUEST
. This is useful if you do not know if form data is coming from the query string, post data, delete data, put data, or patch data. If the request body was JSON,getInput()
returns the JSON property with the input name.
Put Data
$request->getPut()->get('foo');
Note: This is only populated with
x-www-form-urlencoded
content type.getPut()
returns aCollection
object.
Patch Data
$request->getPatch()->get('foo');
Note: This is only populated with
x-www-form-urlencoded
content type.getPatch()
returns aCollection
object.
Delete Data
$request->getDelete()->get('foo');
Note: This is only populated with
x-www-form-urlencoded
content type.getDelete()
returns aCollection
object.
Cookies
$request->getCookies()->get('foo');
Note: This is similar to the data in
$_COOKIE
.getCookies()
returns aCollection
object.
Server Data
$request->getServer()->get('foo');
Note: This is similar to the data in
$_SERVER
.getServer()
returns aCollection
object.
Header Data
$request->getHeaders()->get('foo');
Note: These are the $_SERVER values whose names with with "HTTP_".
getHeaders()
returns aCollection
object. Their names are case-insensitive per RFC 2616.
File Data
$request->getFiles()->get('foo');
Note: This is similar to the data in
$_FILES
.getFiles()
returns aFiles
object.
Opulence converts $_FILES
data into an array of Opulence\Http\Requests\UploadedFile
objects. This provides an easy-to-use wrapper around PHP's built-in upload capabilities. Each UploadedFile
object extends \SplFileInfo
and adds the following methods:
// The error code for the uploaded file (UPLOAD_ERR_OK indicates no error)
$uploadedFile->getError();
// The actual mime type of the uploaded file (secure)
$uploadedFile->getMimeType();
// The extension claimed by the uploaded file (not secure)
$uploadedFile->getTempExtension();
// The mime type claimed by the uploaded file (not secure)
$uploadedFile->getTempMimeType();
// The temporary filename of the uploaded file
$uploadedFile->getTempFilename();
// Whether or not the uploaded file has any errors besides UPLOAD_ERR_OK
$uploadedFile->hasErrors();
// Moves the temporary file to the specified directory/name
$uploadedFile->move($targetDirectory, $name);
Env Data
$request->getEnv()->get('foo');
Note: This is similar to the data in
$_ENV
.getEnv()
returns aCollection
object.
Getting the Path
$request->getPath();
Checking the Path
Opulence allows you to check if a certain path is the current path using $request->isPath(PATH_TO_MATCH)
. It also allows you to use a regular expression for more complex matching:
// The second parameter lets the request know that we're using a regular expression
$request->isPath('/docs/.*', true);
Note: Do not include regular expression delimiters in your regular expression.
Getting the Method
To determine which HTTP method was used to make a request (eg "GET" or "POST"), use getMethod()
:
$request->getMethod();
Spoofing HTTP Methods
HTML forms only permit GET
and POST
HTTP methods. You can spoof other methods by including a hidden input named "_method" whose value is the method you'd like to spoof:
<form method="POST">
<input type="hidden" name="_method" value="DELETE">
...
</form>
If you are using Fortune for your views, you may use the httpMethodInput()
view function:
<form method="POST">
{{! httpMethodInput("DELETE") !}}
...
</form>
You can also use the X-HTTP-METHOD-OVERRIDE
header to set the HTTP method.
Body
The body of a request comes from the php://input
stream. It can be used to grab non-form data, such as JSON and XML data.
JSON
Opulence can accept JSON as input, which makes it easy to start developing REST applications:
$request->getJsonBody();
You can check if a request is JSON:
$request->isJson();
Raw Body
If you want access to the raw request body, run:
$request->getRawBody();
AJAX
To determine if a request was made by AJAX, call:
$request->isAjax();
Getting the Client IP Address
$request->getClientIPAddress();
Checking if HTTPS
$request->isSecure();
Getting the Full URL
$request->getFullUrl();
Checking the Full URL
Opulence allows you to check if a certain URL is the current URL using $request->isUrl(URL_TO_MATCH)
. It also allows you to use a regular expression for more complex matching:
// The second parameter lets the request know that we're using a regular expression
$request->isUrl("http://mysite\.com/posts/.*", true);
Note: Do not include regular expression delimiters in your regular expression.
Getting the Previous URL
$request->getPreviousUrl();
Note: This only works when using the session middleware.
Authentication Data
$phpAuthUser = $request->getUser();
$phpAuthPassword = $request->getPassword();
Using Proxies
If you're using a load balancer or some sort of proxy server, you'll need to add it to the list of trusted proxies:
Request::setTrustedProxies(['192.168.128.41']);
If you want to use your proxy to set trusted headers, then specify their names:
use Opulence\Http\Requests\RequestHeaders;
Request::setTrustedHeaderName(RequestHeaders::CLIENT_IP, 'X-Proxy-Ip');
Request::setTrustedHeaderName(RequestHeaders::CLIENT_HOST, 'X-Proxy-Host');
Request::setTrustedHeaderName(RequestHeaders::CLIENT_PORT, 'X-Proxy-Port');
Request::setTrustedHeaderName(RequestHeaders::CLIENT_PROTO, 'X-Proxy-Proto');
Note: If you're using the skeleton project, then a bootstrapper would be a good place to set the proxy settings.
Responses
Opulence also wraps an HTTP response into the Opulence\Http\Responses\Response
class. You can set the content, HTTP status code, headers, and cookies in a response. Opulence also supports JSON responses and redirects.
Status Codes
By default, a status code of 200 (HTTP OK) is returned. A full list of codes is available in Opulence\Http\Responses\ResponseHeaders
. For example, here's how to set an "Unauthorized" status code:
use Opulence\Http\Responses\Response;
use Opulence\Http\Responses\ResponseHeaders;
$response = new Response('Permission denied', ResponseHeaders::HTTP_UNAUTHORIZED);
$response->send();
Headers
You can specify any headers you'd like in your response. To do something like set a "Content-Type" header to an octet stream, do the following:
use Opulence\Http\Responses\Response;
use Opulence\Http\Responses\ResponseHeaders;
$response = new Response('Foo');
$response->getHeaders()->set('Content-Type', ResponseHeaders::CONTENT_TYPE_OCTET_STREAM);
Cookies
Setting Cookies
Cookies are meant to help you remember information about a user, such as authentication credentials or site preferences. Opulence wraps a cookie into the Opulence\Http\Responses\Cookie
class. To create a cookie, first create a Cookie
object. Then, add it to the Response
object's headers so that it will be sent to the user.
use DateTime;
use Opulence\Http\Responses\Cookie;
// This should look pretty familiar to PHP's setcookie() function
$userIdCookie = new Cookie('id', 17, new DateTime('+1 week'), '/', '.foo.com', true, true, 'lax');
$response->getHeaders()->setCookie($userIdCookie);
$response->send();
Note: Unlike PHP's
setcookie()
, Opulence defaults to setting thehttpOnly
flag to true. This makes sites less prone to cross-site request forgeries.
Deleting Cookies
Deleting a cookie is easy:
// Let's delete the cookie we set in the example above
$response->getHeaders()->deleteCookie('id', '/', '.foo.com', true, true);
$response->send();
JSON Responses
JSON responses are great for API calls. Opulence supports JSON responses in the Opulence\Http\Responses\JsonResponse
class. It accepts either an array
or ArrayObject
as its content.
use Opulence\Http\Responses\JsonResponse;
use Opulence\Http\Responses\ResponseHeaders;
$response = new JsonResponse(['message' => 'Hello, world!'], ResponseHeaders::HTTP_OK);
$response->send();
This will yield the following JSON:
{"message": "Hello, world!"}
Redirect Responses
You'll often finding yourself wanting to redirect a user after things like logging in or out or after filling out a form. Use an Opulence\Http\Responses\RedirectResponse
:
use Opulence\Http\Responses\RedirectResponse;
use Opulence\Http\Responses\ResponseHeaders;
$response = new RedirectResponse('http://www.example.com/login', ResponseHeaders::HTTP_FOUND);
$response->send();
Stream Responses
If your response should be sent as a stream, use Opulence\Http\Responses\StreamResponse
. Simply pass a callback that outputs the contents:
use Opulence\Http\Responses\StreamResponse;
$response = new StreamResponse(function () {
echo 'My awesome stream';
// To make sure the output gets sent, flush it
flush();
});
Note:
StreamResponse
does not let you use the methodsetContent()
. Instead, pass in the callback in the constructor or in thesetStreamCallback()
method.