Skip to content
PHP and MySQL Security: Errors, Attack Types and Protection Methods

PHP and MySQL Security: Errors, Attack Types and Protection Methods

This article discusses security errors that occur when writing web applications based on PHP and MySQL - SQL injection, XSS, CSRF, improper password storage, dangerous files.

1. Introduction

PHP and MySQL — the most widely used technologies for web development. However, it is very easy to break them with incorrectly written code. This article examines dangerous codes, attack methods, and ways to prevent them.

2. The Most Common Security Errors

🔸 a) SQL Injection (Injecting into Queries)

Dangerous code:

$id = $_GET['id'];
$query = "SELECT * FROM users WHERE id = $id";

What happens?

?id=1 OR 1=1

This will output all the users.

Protection method:

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $_GET['id']]);
✅ Use PDO or MySQLi + prepared statements.

🔸 b) XSS (Cross-site Scripting)

Dangerous code:

echo $_GET['name'];
The user sends a link like this:
<script>alert('hacked!')</script>

Protection:

echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');

🔸 c) CSRF (Cross-Site Request Forgery)

The user opens a page and performs harmful actions through your session.

Protection:

  • Add tokens to each POST request.
  • Check the token with $_SESSION.

3. Enhancing MySQL Database Security

🔹 Restrict User Privileges

GRANT SELECT, INSERT ON mydb.* TO 'user'@'localhost';
Never write code using the root user.

🔹 Storing Passwords

Error:

$password = $_POST['password'];

Correct way:

$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);

And to check it:

if (password_verify($input_password, $hash)) {
    // success
}

4. File Upload Security

🔸 Dangerous code:

move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);

🔸 Protection:

  • Allow only permitted file types:
$allowed = ['jpg', 'png', 'pdf'];
  • Rename the file:
$filename = uniqid() . '.' . $ext;

🔹 Preventing Session Hijacking:

ini_set('session.cookie_httponly', 1);
session_start();
session_regenerate_id(true);
setcookie("auth", $token, [
    'expires' => time() + 3600,
    'secure' => true,
    'httponly' => true,
    'samesite' => 'Strict'
]);

6. Additional Security Measures

  • Mandatorily enable HTTPS.
  • Assign proper permissions to files and directories (chmod 755, 644).
  • Hide .env files using .htaccess:
<Files .env>
  Order allow,deny
  Deny from all
</Files>

7. Conclusion

Safety when working with PHP and MySQL is not a choice but an obligation. Treat every piece of information entered by users as untrusted. By securing your code, you protect not only your users but also yourself.

Share