Skip to content

php_ref_http

PHP provides functions to interact directly with the HTTP protocol, primarily for manipulating the HTTP headers sent from the server to the client (browser). These functions allow you to control aspects like cookies, caching, content type, status codes, and redirects before any page content (output) is sent.

Important: Functions that modify HTTP headers (like header(), setcookie(), session_start()) must be called before any output is sent to the browser (including HTML, whitespace before <?php, or echo/print statements). Failure to do so will result in a “Headers already sent” warning or error.

The core HTTP functions discussed here are built into PHP. No separate installation is required.

FunctionDescription
header()Sends a raw HTTP header string. Used for redirects, setting content type, caching directives, security headers, etc.
headers_list()Returns a numerically indexed array of headers scheduled to be sent (or already sent).
headers_sent()Checks if and where headers have already been sent. Useful for debugging “Headers already sent” issues.
setcookie()Sends a Set-Cookie HTTP header to create or modify a cookie on the client’s browser.
setrawcookie()Similar to setcookie(), but sends the cookie value without URL encoding.
http_response_code()Gets or sets the HTTP response status code (e.g., 200, 404, 500).

Setting Content Type:

<?php
// Tell the browser to expect JSON data
header('Content-Type: application/json');
echo json_encode(['status' => 'success', 'data' => [1, 2, 3]]);
?>

Performing a Redirect:

<?php
// Redirect to another page (common practice)
header('Location: /new-page.php');
exit; // Important: Stop script execution after sending redirect header
?>

Setting a Cookie:

<?php
$cookie_name = "user_preference";
$cookie_value = "dark_theme";
$expiry = time() + (86400 * 30); // Expires in 30 days (86400 seconds/day)
$path = "/"; // Available for the entire domain
setcookie($cookie_name, $cookie_value, $expiry, $path);
// Rest of the page content...
echo "Cookie '{$cookie_name}' has been set.";
?>

Setting Response Code:

<?php
// Indicate a resource was not found
http_response_code(404);
echo "Error 404: Page Not Found";
?>

The header() function is crucial for setting HTTP security headers, which help protect your application and users from various attacks. Common examples include:

  • Content-Security-Policy (CSP): Mitigates XSS attacks by specifying allowed sources for content.
  • Strict-Transport-Security (HSTS): Enforces HTTPS connections.
  • X-Frame-Options: Prevents clickjacking by controlling if the page can be embedded in frames.
  • X-Content-Type-Options: Prevents MIME-sniffing attacks.
  • Referrer-Policy: Controls how much referrer information is sent.

Example setting a basic CSP header:

<?php
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com;");
// ... rest of your page ...
?>

While these core functions are fundamental, modern PHP frameworks often abstract HTTP interactions using PSR-7 (HTTP Message Interfaces). PSR-7 defines standard interfaces for HTTP request and response objects, allowing for more structured, testable, and interoperable code when dealing with HTTP.

Frameworks typically provide Request and Response objects that manage headers, cookies, status codes, and the body, often hiding the direct use of functions like header() or setcookie() from the application developer.