Web & Security · 8 min read · Beginner
JSON APIs & Web Security Basics
Encode and decode JSON cleanly, prevent XSS with htmlspecialchars(), and stop SQL injection with PDO prepared statements.
What you'll learn
- Serialize and parse API payloads with json_encode() and json_decode()
- Escape untrusted HTML output with htmlspecialchars(..., ENT_QUOTES, 'UTF-8')
- Understand why PDO prepared statements with ? or :named placeholders stop SQL injection
When PHP renders HTML or queries SQL databases, two habits protect your users from the two most common web vulnerabilities:
- Prevent XSS: Escape user text before printing into HTML using
htmlspecialchars($text, ENT_QUOTES, 'UTF-8'). - Prevent SQL Injection: Always use PDO prepared statements (
prepare()+execute([$param])) instead of concatenating variables into SQL strings.
✓ Safe PDO Prepared Statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch(); ✕ Vulnerable SQL Concatenation
// NEVER concatenate user input into SQL!
$pdo->query("SELECT * FROM users WHERE email = '$email'"); Fill-in-the-Blank Exercise
Safe Output & JSON Encoding
Escape untrusted HTML text and encode a PHP array into a JSON string.
$safe = ($input, ENT_QUOTES, 'UTF-8');
$json = (['status' => 'ok'], JSON_THROW_ON_ERROR);Try It Yourself
PHPHTML Escaping & JSON API Payload
PHP 8 Output (WebAssembly)
Click Run PHP to execute real PHP 8 right in your browser.
Check Your Understanding
Score: 0 / 1
1. What is the standard, reliable way to prevent SQL injection in PHP?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.