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=1This 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 theroot 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:
- Rename the file:
5. Session and Cookie Security
๐น Preventing Session Hijacking:
php CopyEdit ini_set('session.cookie_httponly', 1); session_start(); session_regenerate_id(true);๐น Cookie Settings:
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
.envfiles using.htaccess:
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.