HTTP Request and Response Structure
Anatomy of an HTTP Request
An HTTP request consists of four parts:
GET /catalog/product/view?id=123 HTTP/1.1
Host: magento-store.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/xhtml+xml
Cookie: PHPSESSID=abc123; form_key=XyZ789
| Part | Description | Example |
|---|---|---|
| Method | Action to perform | GET, POST, PUT, DELETE |
| Path | Resource identifier | /catalog/product/view?id=123 |
| Version | HTTP version | HTTP/1.1, HTTP/2 |
| Headers | Metadata about request | Host, User-Agent, Accept |
| Body | Data sent (POST only) | Form data or JSON payload |
Anatomy of an HTTP Response
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Length: 45213
Cache-Control: max-age=3600
Set-Cookie: PHPSESSID=abc123; Path=/; HttpOnly
<!DOCTYPE html>
<html>
<head><title>Product Page</title></head>
<body>...</body>
</html>
| Part | Description | Example |
|---|---|---|
| Status | Result of request | 200 OK, 404 Not Found |
| Headers | Response metadata | Content-Type, Cache-Control |
| Body | The actual content | HTML, JSON, image data |
PHP: Reading Request Data
<?php
// Get the HTTP method
$method = $_SERVER['REQUEST_METHOD']; // GET, POST, etc.
// Get request headers
$accept = $_SERVER['HTTP_ACCEPT']; // text/html,application/xhtml+xml
$userAgent = $_SERVER['HTTP_USER_AGENT'];
// Get query string parameters (GET)
$productId = $_GET['id'] ?? null;
// Get POST body data
$name = $_POST['name'] ?? null;
// Read raw request body (for JSON API requests)
$rawBody = file_get_contents('php://input');
$jsonData = json_decode($rawBody, true);
// Get all headers
$headers = getallheaders();
// Get specific header
$authHeader = $headers['Authorization'] ?? null;
PHP: Sending Responses
<?php
// Set status code
http_response_code(200);
// Or
header('HTTP/1.1 200 OK');
// Set response headers
header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('X-Custom-Header: SomeValue');
// Send JSON response
echo json_encode([
'status' => 'success',
'data' => [
'id' => 1,
'name' => 'Widget Pro',
'price' => 29.99
]
]);
// Set cookies
setcookie(
'recently_viewed',
'123,456,789',
time() + (86400 * 30), // 30 days
'/',
'magento-store.com',
true, // secure
true // httponly
);
Real-World HTTP Exchange
Browser sends:
POST /rest/V1/products HTTP/1.1
Host: magento-store.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
{
"product": {
"name": "New Widget",
"price": 29.99,
"status": 1
}
}
Server responds:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 456,
"name": "New Widget",
"price": 29.99,
"status": 1,
"sku": "WDG-001"
}
TLS/SSL and HTTPS
Why HTTPS Matters
HTTPS = HTTP + TLS (Transport Layer Security). It provides:
- Encryption - Data is encrypted in transit
- Authentication - Server identity is verified by certificates
- Integrity - Data cannot be tampered with
For Magento stores handling payments, HTTPS is mandatory.
The TLS Handshake Process
Client (Browser) Server
| |
|--- ClientHello ----------------->| (supported ciphers, TLS version)
| |
|<-- ServerHello ------------------| (chosen cipher, certificate)
|<-- Certificate ------------------| (server's public key)
|<-- ServerHelloDone --------------|
| |
|--- ClientKeyExchange ----------->| (pre-master secret encrypted with public key)
|--- ChangeCipherSpec ------------>| (switching to encrypted)
|--- Finished -------------------->| (encrypted)
| |
|<-- ChangeCipherSpec --------------| (switching to encrypted)
|<-- Finished --------------------| (encrypted)
| |
|<===== Encrypted Data ============>|
TLS Versions
| Version | Status | Notes |
|---|---|---|
| TLS 1.0 | Deprecated | Vulnerable to BEAST attack |
| TLS 1.1 | Deprecated | No longer secure |
| TLS 1.2 | Supported | Current minimum standard |
| TLS 1.3 | Recommended | Faster handshake, stronger encryption |
PHP: Working with SSL/TLS
<?php
// Make an HTTPS request with certificate verification
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.magento-store.com/rest/V1/products',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => '/path/to/certificate-bundle.crt',
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
CURLOPT_TIMEOUT => 30
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
// Common SSL errors:
// CURLE_SSL_CACERT - Certificate verification failed
// CURLE_SSL_CERT - Invalid certificate
echo "SSL Error: $error";
}
curl_close($ch);
// Check if current request is HTTPS
$isSecure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
// Force HTTPS redirect (common in Magento)
if (!$isSecure) {
$redirectUrl = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header("Location: $redirectUrl");
exit;
}
Magento and HTTPS
Magento enforces HTTPS for:
- Admin panel
- Checkout pages
- Customer account pages
- API endpoints
The base_url in core_config_data should use https:// for production stores.
HTTP/2 and HTTP/3
HTTP/1.1 Limitations
HTTP/1.1 has significant performance limitations:
- One request per connection (without pipelining)
- Header repetition - Same headers sent with every request
- Head-of-line blocking - Requests must be processed in order
- Text-based protocol - Larger payloads
HTTP/2 Improvements
HTTP/2 introduced:
- Multiplexing - Multiple requests over a single TCP connection
- Header compression (HPACK) - Reduces overhead
- Server push - Server can send resources before client requests them
- Binary framing - More efficient parsing
HTTP/2 Comparison
HTTP/1.1: HTTP/2:
Request 1 -----> Request 1 ---->
Response 1 <----- Request 2 ----> (parallel)
Request 2 -----> Request 3 ---->
Response 2 <----- Response 1 <-----
Request 3 -----> Response 2 <-----
Response 3 <----- Response 3 <-----
HTTP/3 (QUIC)
HTTP/3 uses QUIC protocol instead of TCP:
| Feature | HTTP/2 (TCP) | HTTP/3 (QUIC) |
|---|---|---|
| Transport | TCP + TLS 1.2+ | QUIC (built-in TLS 1.3) |
| Head-of-line blocking | Yes (TCP level) | No (per-stream) |
| Connection setup | 2-3 RTT | 0-1 RTT |
| Connection migration | No | Yes (survives network changes) |
PHP: Detecting HTTP Version
<?php
// Check which HTTP version is being used
$protocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
echo "Using: $protocol\n";
// HTTP/2 server push (requires specific web server config)
// In Apache with mod_http2:
// Header set Link "</style.css>; rel=preload; as=style"
// Response headers for HTTP/2
header('Content-Type: application/json');
header('X-Http-Version: ' . ($protocol ?? 'unknown'));
// Common Magento performance headers
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
Magento Performance with HTTP/2
To enable HTTP/2 in Magento:
- Nginx: Add
http2directive
server {
listen 443 ssl http2;
server_name magento-store.com;
# ... SSL configuration
}
- Apache: Enable mod_http2
Protocols h2 h2c http/1.1
- Varnish - Ensure Varnish passes through HTTP/2 headers properly
Key Takeaway
HTTP/2 and HTTP/3 significantly improve web performance through multiplexing, compression, and reduced latency. For Magento stores, enabling HTTP/2 is a quick win for page load speed.
Quiz
1. What are the four main parts of an HTTP request?
2. What does TLS provide that plain HTTP does not?
3. What is the key improvement of HTTP/2 over HTTP/1.1?
4. How many round-trips does it take to establish an HTTP/3 connection?
5. In PHP, how do you read raw JSON request body data?
Flashcards
Question
What are the four parts of an HTTP request?
Click to reveal answer
Answer
Method (GET/POST), Path + Version (/path HTTP/1.1), Headers (metadata), Body (data payload for POST/PUT).
Question
What does TLS stand for and what does it do?
Click to reveal answer
Answer
Transport Layer Security. It encrypts data in transit, authenticates server identity via certificates, and ensures data integrity.
Question
What is the difference between HTTP/1.1, HTTP/2, and HTTP/3?
Click to reveal answer
Answer
HTTP/1.1: Text-based, one request per connection. HTTP/2: Binary, multiplexing, header compression. HTTP/3: Uses QUIC instead of TCP, 0-1 RTT setup, no head-of-line blocking.
Question
Why is HTTPS mandatory for Magento stores?
Click to reveal answer
Answer
Magento handles payment data, customer information, and authentication tokens. HTTPS encrypts this sensitive data, prevents man-in-the-middle attacks, and is required by PCI DSS.
Question
How do you read raw JSON body data in PHP?
Click to reveal answer
Answer
Use file_get_contents('php://input') to read the raw request body. The $_POST superglobal only works for form-encoded data, not JSON.
Question
What is multiplexing in HTTP/2?
Click to reveal answer
Answer
Multiplexing allows multiple HTTP requests and responses to be sent simultaneously over a single TCP connection, eliminating head-of-line blocking.
Question
What header forces browsers to use HTTPS?
Click to reveal answer
Answer
Strict-Transport-Security (HSTS): header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
Question
What is the TLS handshake?
Click to reveal answer
Answer
The process where client and server negotiate security parameters: ClientHello (supported ciphers) -> ServerHello (chosen cipher + certificate) -> Key exchange -> Encrypted communication begins.
Revision Notes
Key Takeaways
- 1. HTTP requests consist of method, path/version, headers, and body
- 2. HTTP responses include status code, headers, and content body
- 3. TLS encrypts communication and authenticates servers via certificates
- 4. HTTP/2 adds multiplexing, header compression, and binary framing
- 5. HTTP/3 uses QUIC protocol for even faster, more reliable connections
- 6. PHP uses $_SERVER for request metadata, $_GET/$_POST for parameters, and file_get_contents('php://input') for raw body
Interview Tips
- • Explain the TLS handshake process step by step
- • Know the difference between HTTP/1.1, HTTP/2, and HTTP/3
- • Understand why HTTPS is essential for e-commerce
- • Be able to read both request and response headers in PHP
- • Explain what multiplexing means and why it improves performance
Cheat Sheet
HTTP Protocol Cheat Sheet
Request Structure:
METHOD /path HTTP/version\r\nHeader: Value\r\n\r\nBody
Response Structure:
HTTP/version STATUS Reason\r\nHeader: Value\r\n\r\nBody
TLS Handshake:
- ClientHello (ciphers, TLS version)
- ServerHello (certificate, chosen cipher)
- Key exchange
- Encrypted communication
HTTP Versions:
- HTTP/1.1: Text, sequential requests
- HTTP/2: Binary, multiplexed, compressed headers
- HTTP/3: QUIC protocol, 0-1 RTT, no head-of-line blocking
PHP Request/Response:
$_SERVER['REQUEST_METHOD'] // GET/POST
$_SERVER['HTTP_ACCEPT'] // Accept header
file_get_contents('php://input') // Raw body
http_response_code(200) // Set status
header('Content-Type: ...') // Set header