PHPPHP

PHP: Web – code examples

Contents

Processing a Form (POST)

Web#post#form#validation#filter_var
Use case: Receive and validate a contact form, registration or comment feature.
<?php
$fehler = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $email = trim($_POST["email"] ?? "");
    $text = trim($_POST["text"] ?? "");
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $fehler[] = "Invalid email"; }
    if (mb_strlen($text) < 10) { $fehler[] = "Message too short"; }
    if (!$fehler) {
        // save or send ...
        header("Location: danke.php");
        exit;
    }
}
foreach ($fehler as $f) { echo "<p>", htmlspecialchars($f), "</p>"; }

Flow: validate, on success finish with a redirect (Post/Redirect/Get), otherwise show errors. Always escape output.

Session and Login Protection

Web#session#login#cookie
Use case: Recognize logged-in users and protect pages.
<?php
session_start();

if (isset($_GET["login"])) {
    session_regenerate_id(true);
    $_SESSION["user"] = "ada";
}
if (!isset($_SESSION["user"])) {
    http_response_code(401);
    exit("Please log in (?login=1)");
}
$_SESSION["seiten"] = ($_SESSION["seiten"] ?? 0) + 1;
echo "Hello {$_SESSION["user"]}, page views: {$_SESSION["seiten"]}";

The session ID lives in the cookie, the data on the server. This passwordless demo login is for illustration only – real logins check password_verify. session_regenerate_id(true) prevents session fixation.

HTTP Request with cURL

Web#curl#http#api#json
Use case: Fetch data from an external web API, e.g. weather, GitHub or payment services.
<?php
$ch = curl_init("https://api.github.com/repos/php/php-src");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HTTPHEADER => ["User-Agent: ProgrammAtlas-Demo", "Accept: application/json"],
]);
$antwort = curl_exec($ch);
if ($antwort === false) {
    exit("Error: " . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$daten = json_decode($antwort, true, 512, JSON_THROW_ON_ERROR);
echo $status, " ", $daten["full_name"], " ", $daten["stargazers_count"], "\n";

Requires the cURL extension. Always set a timeout and check errors and the status code. In larger projects you use a client like Guzzle or Symfony HttpClient.