# PHP Security Best Practices

Security is a critical aspect of web development. PHP applications are often targeted due to their popularity. Here are some best practices to secure your PHP code.

---

## 1. SQL Injection (SQLi)
SQL injection occurs when malicious SQL statements are inserted into entry fields for execution.

**Prevention:** Always use **Prepared Statements** (with PDO or MySQLi) instead of concatenating strings.

```php
// BAD (Vulnerable)
$sql = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";

// GOOD (Secure)
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $_POST['email']]);
$user = $stmt->fetch();
```

## 2. Cross-Site Scripting (XSS)
XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users.

**Prevention:** Always sanitize output using `htmlspecialchars()` when displaying user-submitted data.

```php
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
```

## 3. Cross-Site Request Forgery (CSRF)
CSRF forces an end user to execute unwanted actions on a web application in which they're currently authenticated.

**Prevention:** Use anti-CSRF tokens in forms.

```php
// Generate token
$_SESSION['token'] = bin2hex(random_bytes(32));

// In HTML form
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>">

// Verify on POST
if (!hash_equals($_SESSION['token'], $_POST['token'])) {
    die("CSRF validation failed");
}
```

## 4. Password Hashing
Never store passwords in plain text. Use PHP's built-in password hashing functions.

```php
$hash = password_hash($password, PASSWORD_DEFAULT); // Create hash
if (password_verify($input_password, $hash)) { ... } // Verify
```

[[programming/php/php]] [[programming/php/php-forms]]