HTTP Protocol

The Request-Response

Client-Server Protocol

study-group-01

Created by Juan Manuel Torres / @onema / onema.io


Follow Live

http://slides.com/onema/http-protocol/live

HTTP Basics - The Web

The internet is a massive distributed Client-Server system.

HTTP Stateless Protocol

HTTP allows a variety of hosts and clients to communicate.
In order to make this possible each request knows nothing about previous requests (Stateless).

HTTP - Request - Response

Communication between client and host starts when the client sends a request to the server.
The server processes the request and generates a response that is sent back to the client.

Request

The request is a message sent from the client to an HTTP server "requesting" access to a resource. A resource is information that can be identified by a URL, e.g. an image, file, html, etc.


Response

The response is a message sent by the HTTP server back to the client usually containing the resource that was requested.

The Uniform Resource Locator (URL)


Structure of HTTP Messages

Request and Response messages are similar:
  • Initial Line: Request/Response line
  • Request/Response Headers
  • An empty line
  • Optional message body

Request Message

GET /profile/me.html HTTP/1.1
Host: www.website.com
Accept: text/html       
The Request line is the most important in the message and it contains:
  1. HTTP Method (GET)
  2. URI
  3. HTTP Version
The client MUST include the Host header field in all HTTP/1.1 requests.

Response Message

HTTP/1.1 200 OK
Date: Sat, 02 Apr 2011 21:05:05 GMT
Server: lighttpd/1.4.19
Content-Type: text/html; charset=UTF-8                    
The Response line, AKA Status Line, contains:
  1. HTTP Version
  2. Response Status Code
  3. Reason Phrase
The response headers indicate the date, server type and the response body type.

Header types

Not all headers are made equal:
  • General header: can be used in both request and response
  • Request header: only applicable to request messages
  • Response header: only applicable to response messages
  • Entity header: define meta-information about the body

HTTP Verbs

The action that should be performed in the host server is set using HTTP verbs.
  • GET: get an existing resource (Safe and Idempotent Method)
  • POST: send data to the server e.g. create new resource (Not Safe nor Idempotent)
  • PUT: Update or create an resource (Not Safe but Idempotent)
  • DELETE: Delete a resource (Not Safe but Idempotent)

Status Codes

All Responses contains status codes. Codes are important because they have a meaning
  • Informational 1xx: Indicate a provisional response
  • Successful 2xx: Indicate that the client request was successful
  • Redirection 3xx: Indicates that further action is needed
  • Client Error 4xx Indicates when the client seems to have erred
  • Internal Server Error 5xx: Indicates cases in which the server is aware that it has erred

Handling request in PHP

All request information will be contained within the $_REQUEST super-global.
GET /test.php?hello=hola&world=mundo! HTTP/1.1
Host: dev.sandbox.io:8080
Accept: application/json
Cache-Control: no-cache          
print_r($_REQUEST);

print_r(parseRequestHeaders());


function parseRequestHeaders() {
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) != 'HTTP_') {continue;}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
return $headers;
}

The results


Array
(
    [hello] => hola
    [world] => mundo!
)
Array
(
    [Host] => dev.sandbox.io:8080
    [Connection] => keep-alive
    [Accept] => application/json
    [Cache-Control] => no-cache
    [User-Agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
    [Accept-Encoding] => gzip,deflate,sdch
    [Accept-Language] => en-US,en;q=0.8,es;q=0.6
)
                    

Request/Response application

Using Symfony HTTP Foundation

The gola of the HttpFoundation is to "replace the default PHP global variables and functions by an Object-Oriented layer"[13]
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();

$hello = $request->query->get('hello');
$world = $request->query->get('world');

$response = new Response(
$hello . ' ' . $world .'!',
Response::HTTP_OK,
['content-type' => 'text/html']
);

$response->send();

Request Methods

// the URI being requested (e.g. /about) minus any query parameters
$request->getPathInfo();

// retrieve GET and POST variables respectively
$request->query->get('foo');
$request->request->get('bar', 'default value if bar does not exist');

// retrieve SERVER variables
$request->server->get('HTTP_HOST');

// retrieves an instance of UploadedFile identified by foo
$request->files->get('foo');

// retrieve a COOKIE value
$request->cookies->get('PHPSESSID');

// retrieve an HTTP request header, with normalized, lowercase keys
$request->headers->get('host');
$request->headers->get('content_type');

$request->getMethod(); // GET, POST, PUT, DELETE, HEAD
$request->getLanguages(); // an array of languages the client accepts

Response methods


use Symfony\Component\HttpFoundation\Response;
$response = new Response();

$response->setContent('<html><body><h1>Hello world!</h1></body></html>');
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'text/html');

// prints the HTTP headers followed by the content
$response->send();

Next time Symfony2 Kernel



THE END

BY Juan Manuel Torres / onema.io / @onema

References

[1] http://tools.ietf.org/html/rfc2616#section-9.5 
[2]http://tools.ietf.org/html/rfc2616#page-128 
[3]http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html 
[4]http://www.ntu.edu.sg/home/ehchua/programming/webprogramming/HTTP_Basics.html 
[5] http://code.tutsplus.com/tutorials/http-the-protocol-every-web-developer-must-know-part-1--net-31177 
[6] http://symfony.com/doc/current/book/http_fundamentals.html 
[7] http://www.jmarshall.com/easy/http/ 
[8] http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol 
[9] http://www.tutorialspoint.com/http/http_requests.htm 
[10] http://symfony.com/doc/current/components/http_foundation/introduction.html 
[11] http://php.net/manual/en/reserved.variables.request.php 
[12] http://stackoverflow.com/questions/541430/how-do-i-read-any-request-header-in-php
[13] http://fabien.potencier.org/article/51/create-your-own-framework-on-top-of-the-symfony2-components-part-2

HTTP Protocol

By Juan Manuel Torres

HTTP Protocol

  • 3,450