Introduction: Why is PHP so treacherous for beginners?
PHP remains one of the most popular languages for web development, but its low entry threshold often leads to the formation of bad habits. Beginning developers, inspired by the simplicity of the syntax, often forget about security, performance, and modern standards. In this article, we will analyze the top mistakes of beginning PHP developers that can turn your code into a nightmare for maintenance and a vulnerability for attacks.
We won't just list the problems — you will see PHP code examples with errors and their corrected versions. This will help you immediately apply correct practices.
1. Ignoring Security: SQL Injections and XSS
The most critical mistake is trusting user data. Beginners often insert variables directly into SQL queries or output them to the page without filtering.
Mistake: Concatenation in SQL queries
A classic example of a vulnerability:
// INCORRECT: vulnerable to SQL injection$id = $_GET['id'];$query = "SELECT * FROM users WHERE id = $id";$result = mysqli_query($link, $query);An attacker can pass ?id=1 OR 1=1 and get all data from the table.
Solution: Prepared Statements (PDO)
Use PDO or mysqli with prepared statements:
// CORRECT: PDO with prepared statement$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");$stmt->execute(['id' => $_GET['id']]);$result = $stmt->fetchAll();Mistake: Outputting data without escaping (XSS)
If you output data from the database or $_GET directly, you risk an XSS attack:
// INCORRECT: XSS vulnerabilityecho "Hello, " . $_GET['name'];Solution: htmlspecialchars
Always escape output:
// CORRECT: HTML escapingecho "Hello, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');2. Using Deprecated Constructs and Functions
Many textbooks from 10 years ago teach using mysql_* functions or short tags. This is not only unsafe but may also not work on modern hosting.
Mistake: mysql_* functions
// INCORRECT: deprecated extension$link = mysql_connect('localhost', 'user', 'pass');mysql_select_db('test', $link);This extension was removed in PHP 7, and the code will simply crash with an error.
Solution: Switch to PDO or MySQLi
// CORRECT: PDO - modern and secure approach$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');Mistake: Short tags
// INCORRECT: may be disabled in php.ini<? echo "Hello"; ?>Solution: Only full tags
// CORRECT: always use <?php<?php echo "Hello"; ?>3. Poor Work with Forms and Data
Beginning developers often forget to check whether the form was submitted and use $_REQUEST instead of specific superglobal arrays.
Mistake: Lack of request method check
// INCORRECT: code executes even on GET request$name = $_POST['name'];// ... processingSolution: Check REQUEST_METHOD
// CORRECT: check that the form was submittedif ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name'] ?? ''; // ... validation and processing}Mistake: Using $_REQUEST
The superglobal array $_REQUEST combines GET, PO