PhPHP · Lesson 7 of 8

Handling Web Requests

PHP's home turf: a form posts to your script, you read the input, talk to a database, and print HTML. Here's the raw version every framework abstracts.

PHP
<?php
// form.php — serve with: php -S localhost:8000
// $_GET  = query string params (?name=Ada)
// $_POST = submitted form fields

$name = $_POST['name'] ?? '';
?>
<!DOCTYPE html>
<html><body>
  <form method="post">
    <input name="name" placeholder="Your name">
    <button>Say hi</button>
  </form>

  <?php if ($name !== ''): ?>
    <!-- htmlspecialchars prevents XSS — ALWAYS escape output -->
    <p>Hello, <?= htmlspecialchars($name) ?>!</p>
  <?php endif; ?>
</body></html>
⚠ Warning
Two security rules cover most PHP vulnerabilities ever written: (1) escape all output with htmlspecialchars() to stop XSS; (2) never concatenate user input into SQL — use prepared statements (PDO below) to stop SQL injection.
PHP
<?php
// PDO — PHP's built-in database layer (works with SQLite,
// MySQL, Postgres...). Prepared statements keep input as data:

$db = new PDO('sqlite:app.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->exec('CREATE TABLE IF NOT EXISTS guests
           (id INTEGER PRIMARY KEY, name TEXT)');

$stmt = $db->prepare('INSERT INTO guests (name) VALUES (?)');
$stmt->execute([$name]);

$rows = $db->query('SELECT name FROM guests')->fetchAll();
foreach ($rows as $row) {
    echo htmlspecialchars($row['name']), "<br>";
}
◆ Note
Each request starts a fresh PHP process state — no memory carries over between requests. That 'shared-nothing' model is why PHP scales so simply, and why sessions ($_SESSION) exist for the state you do want to keep.