PHP Security

📘 PHP 👁 33 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Introduction to PHP Security

PHP security focuses on protecting web applications from common attacks such as SQL Injection, XSS, CSRF, file inclusion, and session hijacking. Secure coding practices are essential for building safe and reliable PHP applications.


Common Security Threats in PHP

  1. SQL Injection

  2. Cross-Site Scripting (XSS)

  3. Cross-Site Request Forgery (CSRF)

  4. File Upload Vulnerabilities

  5. Session Hijacking

  6. Remote & Local File Inclusion


SQL Injection Protection

Always use prepared statements.

Example (PDO)

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]);

Cross-Site Scripting (XSS)

XSS occurs when malicious scripts are injected into web pages.

Prevention

echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

Cross-Site Request Forgery (CSRF)

CSRF forces users to perform actions without their consent.

CSRF Token Example

session_start(); $_SESSION['token'] = bin2hex(random_bytes(32));
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>">

Input Validation and Sanitization

Validate Email

filter_var($email, FILTER_VALIDATE_EMAIL);

Sanitize Input

filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);

Secure Password Handling

Never store plain text passwords.

Password Hashing

$hash = password_hash($password, PASSWORD_DEFAULT);

Password Verification

password_verify($password, $hash);

File Upload Security

  • Check file type

  • Limit file size

  • Rename uploaded files

$allowed = ['jpg', 'png', 'pdf']; $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); if (!in_array($ext, $allowed)) { die("Invalid file type"); }

Session Security

Regenerate Session ID

session_regenerate_id(true);

Secure Session Settings

ini_set('session.cookie_httponly', 1); ini_set('session.cookie_secure', 1);

Secure Cookies

setcookie( "user", "Admin", time() + 3600, "/", "", true, true );

Prevent File Inclusion Attacks

  • Disable allow_url_include

  • Validate file paths

  • Avoid dynamic includes


Error Handling & Logging

Do not display errors in production.

ini_set('display_errors', 0); ini_set('log_errors', 1);

Use HTTPS

  • Encrypts data in transit

  • Protects cookies and sessions

  • Improves user trust


Best Practices for PHP Security

  • Keep PHP updated

  • Use HTTPS

  • Validate all user input

  • Escape output

  • Use prepared statements

  • Limit file permissions


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes