Mohamed Sharaf

PHP security: the basics that still matter

XSS, SQL injection, CSRF, file uploads, includes and passwords: the short list every PHP developer needs.

· 1 min read

From the archive: in 2012 I shared a long PHP security guide by another author on my old blog. This is a short, updated version in my own words.

A long PHP security guide from 2012 spent pages on register_globals and “magic quotes”. Both were removed from PHP years ago. What hasn’t changed is the list of mistakes that let attackers in:

  • Cross-site scripting (XSS): never print user input as-is. Escape it for where it goes: htmlspecialchars($value, ENT_QUOTES, 'UTF-8') for HTML, and use a templating engine that escapes by default.
  • SQL injection: never build SQL by joining strings. Use prepared statements (PDO or mysqli) for every query that includes a value.
  • Trusting the form: hidden fields, prices and IDs in a form can all be changed by the user. Validate everything again on the server.
  • CSRF: any form that changes something needs a secret per-session token, and session cookies should be SameSite.
  • File uploads: a door attackers love. I wrote about it separately: File uploads: the door we keep leaving open.
  • Includes and eval(): never let user input decide which file to include or what code to run.
  • Error display: turn display_errors off in production and log errors instead.
  • Passwords: forget MD5 and home-made salting. Use password_hash() and password_verify(); PHP handles the salt and a strong algorithm for you.

For more depth, the OWASP Cheat Sheet Series covers each of these properly.

ShareWhatsAppLinkedInXTelegramFacebook