HTTP Requests/Responses

Table of Contents

  1. Introduction
  2. Requests
    1. Collections
    2. Query String Data
    3. Post Data
    4. Request Data
    5. Put Data
    6. Patch Data
    7. Delete Data
    8. Cookies
    9. Server Data
    10. Header Data
    11. File Data
    12. Env Data
    13. Getting the Path
      1. Checking the Path
    14. Getting the Method
    15. Body
      1. JSON
      2. Raw Body
    16. AJAX
    17. Getting the Client IP Address
    18. Checking if HTTPS
    19. Getting the Full URL
      1. Checking the Full URL
    20. Getting the Previous URL
    21. Authentication Data
    22. Using Proxies
  3. Responses
    1. Status Codes
    2. Headers
    3. Cookies
      1. Setting Cookies
      2. Deleting Cookies
    4. JSON Responses
    5. Redirect Responses
    6. Stream 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:

Query String Data

$request->getQuery()->get('foo');

Note: This is similar to the data in $_GET. getQuery() returns a Collection object.

Post Data

$request->getPost()->get('foo');

Note: This is similar to the data in $_POST. getPost() returns a Collection 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 a Collection object.

Patch Data

$request->getPatch()->get('foo');

Note: This is only populated with x-www-form-urlencoded content type. getPatch() returns a Collection object.

Delete Data

$request->getDelete()->get('foo');

Note: This is only populated with x-www-form-urlencoded content type. getDelete() returns a Collection object.

Cookies

$request->getCookies()->get('foo');

Note: This is similar to the data in $_COOKIE. getCookies() returns a Collection object.

Server Data

$request->getServer()->get('foo');

Note: This is similar to the data in $_SERVER. getServer() returns a Collection object.

Header Data

$request->getHeaders()->get('foo');

Note: These are the $_SERVER values whose names with with "HTTP_". getHeaders() returns a Collection 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 a Files 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 a Collection 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 the httpOnly 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 method setContent(). Instead, pass in the callback in the constructor or in the setStreamCallback() method.