Topics Database & Security PHP Security Best Practices
intermediate 14 min read

PHP Security Best Practices

Password hashing, XSS prevention, CSRF, input validation, and secure configuration.

Password Hashing

// Hash (uses bcrypt by default)
\$hash = password_hash(\$password, PASSWORD_BCRYPT, ['cost' => 12]);

// Verify
if (password_verify(\$password, \$hash)) {
// login
}

// Check if rehash needed
if (password_needs_rehash(\$hash, PASSWORD_ARGON2ID)) {
\$hash = password_hash(\$password, PASSWORD_ARGON2ID);
}

XSS Prevention

// Always escape output
echo htmlspecialchars(\$userInput, ENT_QUOTES, 'UTF-8');

// For URLs
echo urlencode(\$data);

Input Validation

\$email = filter_var(\$_POST['email'], FILTER_VALIDATE_EMAIL);
\$int = filter_var(\$_POST['age'], FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 150]
]);

CSRF

Use CSRF tokens in forms. In Laravel: @csrf.

Examples

<?php
function sanitizeOutput(string $input): string {
    return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
}
$unsafe = "<script>alert('xss')</script>";
echo sanitizeOutput($unsafe);

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.