PHP Security Basics

Protect your application and users.

✍️ 2 exercises in this lesson
  • SQL injection: always use prepared statements.
  • XSS: escape output with htmlspecialchars($value, ENT_QUOTES, 'UTF-8').
  • Passwords: store only hashes with password_hash(); check with password_verify(). Never use md5 or sha1 for passwords.
  • CSRF: include a secret token in forms and verify it on submit.
  • Uploads: check type and size, rename files, and store them outside the web root when possible.
  • Errors: turn display_errors off in production and log errors instead.
  • Keep PHP and your packages up to date.
Frameworks like Laravel handle most of these protections for you out of the box.

Key Takeaways: PHP Security Basics

Mastering PHP Security Basics helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Security Basics Code Example

PHP
<?php
$hash = password_hash("Secret@123", PASSWORD_DEFAULT);
echo strlen($hash) . " character hash<br>";

var_dump(password_verify("Secret@123", $hash));
var_dump(password_verify("wrong", $hash));

$comment = '<script>alert("xss")</script>';
echo "<br>" . htmlspecialchars($comment, ENT_QUOTES, 'UTF-8');
Output
60 character hash
bool(true)
bool(false)
&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

PHP Security Basics Practice Exercises

Check what you learned in “PHP Security Basics”.

/ 2 solved
Fill in the blank

Hash a password for storage.

$hash = ($password, PASSWORD_DEFAULT);
✓ Correct! Not quite. Try again.
Multiple choice

Which function checks a password against its hash?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services