DEV Community

Muhammad Ali Siddiqui
Muhammad Ali Siddiqui

Posted on Edited on

5 Security Mistakes in Native PHP Apps (And How to Fix Them)

When building web applications using native PHP and MySQL, keeping your application secure requires clear defensive programming habits. Here are 5 common security gaps in native setups and how to handle them properly.

1. Raw Queries Instead of Prepared Statements

Passing unsanitized user inputs directly into SQL queries leads to SQL Injection (SQLi).

  • Vulnerable:

php
$query = "SELECT * FROM users WHERE email = '" . $_POST['email'] . "'";

$stmt =$pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' =>$_POST['email']]);
$user =$stmt->fetch();

2. Outputting Direct Input Without Escaping (XSS)
Displaying user input directly on the UI without escaping allows malicious script execution.

echo "<div>" . $_GET['username'] . "</div>";

echo "<div>" . htmlspecialchars($_GET['username'], ENT_QUOTES, 'UTF-8') . "</div>";

3. Weak Password Hashing Logic
Using outdated hashing mechanisms like MD5 or SHA1 makes passwords easy to crack via rainbow tables.

$hashedPassword = md5($password);

$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
// Verification:
if (password_verify($password,$existingHash)) { ... }

4. Missing CSRF Token Verification
Forms submitted without Cross-Site Request Forgery (CSRF) tokens leave state-changing requests exposed to unauthorized triggers.

Generate a secure token per session and check it on form submission:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'],$_POST['csrf_token'])) {
        die("Invalid CSRF token execution.");
    }
}

5. Exposing Database Error Output to Users
Printing raw database errors in production leaks table layouts and backend configuration details.

Fix:
Catch exceptions internally, write them to error logs, and show generic messages to users.

try {
    // Database operation
} catch (PDOException $e) {
    error_log($e->getMessage());
    exit('An internal error occurred. Please try again later.');
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)