Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Forms and request data

A site receives data from a visitor in two ways: from the address bar and from submitted forms. PHP sorts this data into ready-made arrays, so you never parse a request by hand.

The examples in this lesson need a web server, so only the ones that do not depend on a request can be run here.

Data from the URL

Everything after the question mark in a URL ends up in the $_GET array. For /search.php?query=php&page=2 it looks like this:

<?php
 
var_dump($_GET);
// ['query' => 'php', 'page' => '2']

All values arrive as strings — even the number 2.

Reading a single value

A parameter may be absent from the URL, so read it with the ?? operator and a default:

<?php
 
$query = $_GET['query'] ?? '';
$page = (int) ($_GET['page'] ?? 1);

A form

A form sends its data to the URL in the action attribute. A field's name attribute sets the key under which the value arrives in PHP:

<form action="/register.php" method="post">
  <input name="email" type="email">
  <input name="password" type="password">
  <button>Sign up</button>
</form>

With method="post" the data travels in the request body and ends up in the $_POST array. Use it for anything that changes data on the server and anything secret: a password would be visible in the address bar.

Handling the form

<?php
 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
 
    if ($email === '' || $password === '') {
        echo 'Please fill in all fields';
    } else {
        echo 'Form accepted';
    }
}

First check that the form was actually submitted, then read the fields and make sure they are not empty.

Validating data

User data cannot be trusted: an "email" field may contain anything at all. filter_var() validates a value against ready-made rules:

<?php
 
var_dump(filter_var('anna@example.com', FILTER_VALIDATE_EMAIL) !== false); // bool(true)
var_dump(filter_var('not an email', FILTER_VALIDATE_EMAIL) !== false);     // bool(false)

Browser-side checks — the required and type="email" attributes — are convenient for the visitor but do not replace server-side validation: a request can be sent without the form.

Printing data on a page

If you print a user's text as is, the browser will run the tags and scripts it contains. This attack is called XSS. htmlspecialchars() turns dangerous characters into harmless ones:

<?php
 
$comment = '<script>alert(1)</script>';
 
echo htmlspecialchars($comment);

Run the example: instead of a tag you get plain text.

A common mistake

The most dangerous habit is printing data from $_GET and $_POST directly: echo $_GET['name']. Pass everything that comes from the user and ends up on a page through htmlspecialchars().

Thanks for reading!

Donate to the site — we work hard for you.