Preparing your workspace
Secure PHP applications validate untrusted input, protect authentication state, use prepared statements, and escape output according to its context.
User input should always be considered untrusted. Applications need server-side validation, prepared database queries, secure session handling, appropriate output escaping, and protection against common web threats. htmlspecialchars is useful when safely placing text into HTML contexts, but output encoding depends on where the data is being inserted. CSRF protection is important for state-changing browser requests using cookie-based authentication. Security controls should be designed as part of the application rather than added only after features are finished.
A profile update form should validate input, use a protected session, use a parameterized database query, and safely escape values when displaying them back to the user.
<?php
$name = trim($_POST['name'] ?? '');
if ($name === '' || mb_strlen($name) > 100) {
http_response_code(422);
exit('Invalid name');
}
$safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
echo $safeName;The input is validated and safely encoded before being displayed as HTML content.