Validating data and preventing XSS
Two rules govern the security of any form: validate the input (check that the data is what you expect) and escape the output (convert special characters before showing them in HTML). The first protects your application logic; the second prevents the most common attack against web pages, XSS (Cross-Site Scripting). They are two different controls and you need both: validating does not excuse you from escaping, and escaping does not replace validating.
What XSS is and how to prevent it
Imagine a blog comment. If an attacker writes <script>stealSession()</script> and your page prints it as is, every visitor's browser will run that script with your site's privileges: it can steal session cookies, change the content or redirect to fake pages. The defense is to escape all output coming from a user or a database with htmlspecialchars($text, ENT_QUOTES, 'UTF-8'), which converts < to <, > to >, & to & and quotes to entities. The browser shows the text but does not interpret it as code.
<?php
declare(strict_types=1);
function e(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$comment = '<script>alert("hacked")</script>';
echo $comment, "\n"; // dangerous in an HTML page
echo e($comment), "\n";
// <script>alert("hacked")</script>Always escape at output time and according to the context. For HTML use htmlspecialchars; for an attribute, the same, but with quotes always on the attribute; for a URL, urlencode; for JavaScript, json_encode. A small helper function like e() saves you from typing the parameters every time. Do not store already-escaped data in the database: store the original data and escape when displaying it, because the same data may later appear in HTML, in an email or in a PDF, each with different rules.
Validating with filter_var
Validation checks type, format, range and length. PHP provides filter_var for the common cases: FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT (with min_range and max_range options), FILTER_VALIDATE_URL and FILTER_VALIDATE_BOOLEAN. It returns the converted value if valid, or false (or null) if not. Beware of zero: FILTER_VALIDATE_INT returns 0 for '0', which is falsy, so always compare with === false. For text use mb_strlen and check the range; store errors in an array to show them all at once.
<?php
declare(strict_types=1);
/**
* @param array<string, mixed> $input
* @return array{errors: array<string, string>, data: array<string, mixed>}
*/
function validateSignup(array $input): array
{
$errors = [];
$name = trim((string) ($input['name'] ?? ''));
if (mb_strlen($name) < 2 || mb_strlen($name) > 50) {
$errors['name'] = 'Name must have 2 to 50 characters.';
}
$email = filter_var($input['email'] ?? '', FILTER_VALIDATE_EMAIL);
if ($email === false) {
$errors['email'] = 'Invalid email address.';
}
$age = filter_var($input['age'] ?? '', FILTER_VALIDATE_INT, [
'options' => ['min_range' => 18, 'max_range' => 120],
]);
if ($age === false) {
$errors['age'] = 'Age must be a number between 18 and 120.';
}
return ['errors' => $errors, 'data' => ['name' => $name, 'email' => $email, 'age' => $age]];
}
$result = validateSignup(['name' => 'Ana', 'email' => 'ana-at-example', 'age' => '17']);
print_r($result['errors']);
// [email] => Invalid email address.
// [age] => Age must be a number between 18 and 120.理解度チェック
問題 1 / 1What is the main defense against XSS?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字