Login Register
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:

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

What happens?

http CopyEdit ?id=1 OR 1=1

This will output all the users.

Protection method:

php CopyEdit $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:

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

Protection:

php CopyEdit 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

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

๐Ÿ”น Storing Passwords

Error:

php CopyEdit $password = $_POST['password'];

Correct way:

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

And to check it:

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

4. File Upload Security

๐Ÿ”ธ Dangerous code:

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

๐Ÿ”ธ Protection:

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

๐Ÿ”น Preventing Session Hijacking:

php CopyEdit ini_set('session.cookie_httponly', 1); session_start(); session_regenerate_id(true); php CopyEdit 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:
apacheconf CopyEdit <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.