This practical PHP 8.5 tutorial explains PHP Security: XSS, SQL Injection, CSRF, SSRF, and Headers with a small reproducible lab, strict types, secure defaults, verification, and production troubleshooting.
1. Prepare the project
mkdir php-lab
cd php-lab
printf "vendor/n.envnvar/n" > .gitignore
php -v
php -m
2. Implement the example
<?php
declare(strict_types=1);
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$email) { http_response_code(422); }
Save the example in app.php. Use declare(strict_types=1), validate data at trust boundaries, prefer explicit dependencies, and avoid hidden global state.
3. Run the lab
composer audit
vendor/bin/phpstan analyse src
4. Verify the result
curl -I http://127.0.0.1:8080/ | grep -Ei "content-security-policy|x-content-type-options|referrer-policy"
Verify real behavior, not only a zero exit status. Inspect HTTP status and headers, database changes, service logs, file permissions, memory use, and graceful shutdown where applicable.
Troubleshooting
Start with php -l, php --ini, and php -m. Confirm the CLI and PHP-FPM use the intended version and configuration. Then inspect permissions, environment variables, dependency lockfiles, extensions, FPM and web-server logs, upstream connectivity, and timeouts.
Security and production checklist
- Supported PHP and exact Composer dependencies are recorded.
- Output is escaped for its HTML context and SQL uses prepared statements.
- Authentication, authorization, CSRF, session cookies, upload limits, and SSRF controls are explicit.
display_errorsis disabled in production while errors are logged securely.- Tests, static analysis, health checks, backups, resource limits, upgrades, and rollback are verified.
References: PHP manual, supported PHP versions, and Composer documentation.