PHP Tutorial menu

PHP Forms and Sessions

Forms are how visitors send data to your website: contact forms, login forms, admission forms. PHP reads that data on the server.

GET and POST

An HTML form sends its data with one of two methods:

GETPOST
Where data goesIn the URL, like ?q=phpInside the request body
Visible in address barYesNo
Good forSearches, filtersLogins, sign-ups, anything private
Read in PHP with$_GET$_POST

$_GET and $_POST are superglobals: built-in arrays you can use anywhere in your script.

A Simple Form

Save this as contact.php. The form sends its data back to the same file:

Example

php
<!DOCTYPE html>
<html>
<body>

<form method="post" action="contact.php">
  Name: <input type="text" name="name"><br>
  Email: <input type="email" name="email"><br>
  <button type="submit">Send</button>
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = htmlspecialchars($_POST["name"] ?? "");
    echo "<p>Thank you, $name. We will contact you soon.</p>";
}
?>

</body>
</html>
Output
Thank you, Bilal. We will contact you soon.

The name attribute of each input becomes the key in $_POST.

Never Trust User Input

A visitor can type anything into a form, including HTML or JavaScript. If you print it directly, an attacker can run scripts on your page. This attack is called XSS (cross-site scripting).

  • Use htmlspecialchars() every time you print user data into HTML
  • Use trim() to remove extra spaces
  • Check that required fields are not empty
  • Use filter_var() to check emails and numbers

Golden rule: check input when it arrives, and escape it when you print it.

Validating a Form

Example

php
<?php
$errors = [];
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$age = $_POST["age"] ?? "";

if ($name === "") {
    $errors[] = "Name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Please enter a valid email.";
}
if (filter_var($age, FILTER_VALIDATE_INT, ["options" => ["min_range" => 14]]) === false) {
    $errors[] = "Age must be a whole number, 14 or more.";
}

if ($errors) {
    foreach ($errors as $e) {
        echo "<p>" . htmlspecialchars($e) . "</p>";
    }
} else {
    echo "Admission form received. Thank you!";
}

If the visitor leaves the name empty and types ali@ as email, the page shows:

Output
Name is required.
Please enter a valid email.

Sessions

HTTP forgets everything between page loads. A session lets you remember a user, for example after they log in. PHP stores session data on the server and gives the browser a small ID cookie.

Example

php
<?php
// login.php
session_start();
$_SESSION["username"] = "ayesha";
echo "You are logged in.";

Example

php
<?php
// dashboard.php
session_start();

if (!isset($_SESSION["username"])) {
    echo "Please log in first.";
    exit;
}
echo "Welcome back, " . htmlspecialchars($_SESSION["username"]) . "!";
Output
Welcome back, ayesha!

Call session_start() at the very top of each page, before any HTML is sent. To log out, call session_destroy().

Cookies

A cookie is a small piece of data saved in the visitor's browser. Use it for simple, non-secret things like a chosen language.

Example

php
<?php
setcookie("language", "urdu", time() + 60 * 60 * 24 * 30); // 30 days

echo $_COOKIE["language"] ?? "No language saved yet.";

The cookie becomes available in $_COOKIE on the next page load. Never store passwords in cookies.

Exercise

Exercise

Which function should you use before printing user input into HTML?

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp