Urgent.News

What's breaking now, across thousands of outlets.

Tech

SQL Injection en PHP: cómo prevenirlo con consultas preparadas (guía rápida)

La inyección SQL ( SQL Injection ) es una de las amenazas más comunes y peligrosas para una aplicación web: el atacante manipula las consultas SQL que ejecuta tu código para leer, modificar o borrar información que no le corresponde. Puede comprometer la integridad de los datos, exponer información sensible y dañar la reputación de tu sitio. En PHP se evita con pocas costumbres, y la principal es…

Original Spanish Read in English

SQL injection (SQL Injection) is one of the most common and dangerous threats to web applications: attackers manipulate the SQL queries that your code executes to read, modify or delete information that does not belong to them. It can compromise data integrity, expose sensitive data and damage your site's reputation. In PHP, it is prevented through simple habits, the main one being never concatenating user data within a query.

How the attack works When user data is inserted directly into an SQL query, the attacker can alter its logic. This login is vulnerable: $username = $_POST['user']; $password = $_POST['pass']; // Vulnerable query $sql = SELECT * FROM seg_usuario WHERE username = $username AND password = $password; $result = $conn->query($sql); If the attacker sends admin as username and OR 1 = 1 as password, the resulting query is: SELECT * FROM seg_usuario WHERE username = admin AND password = OR 1 = 1.

The condition 1 = 1 is always true, so access is granted without valid credentials. The defense: prepared statements The best way to prevent it is to always separate the query from the data. With prepared statements, the engine first receives the query structure and then the values, which never get interpreted as SQL. With MySQLi: $stmt = $conn->prepare("SELECT * FROM seg_usuario WHERE username = ?

AND password = ?"); $stmt->bind_param("ss", $username, $password); $stmt->execute(); $result = $stmt->get_result(); With PDO, using named parameters: $stmt = $pdo->prepare("SELECT * FROM seg_usuario WHERE username = :username AND password = :password"); $stmt->execute(['username' => $username, 'password' => $password]); Two clarifications.

Parameters only substitute values, not table or column names: if any of them need to be dynamic, validate them against a list of allowed values. And in a real login, passwords are not stored in clear text, password_hash() and password_verify() are used; here direct comparison is kept only to keep the example short. Additional layers Prepared statements are the primary defense, but they should be combined with other measures: Input validation: verify the data has the expected format.

It is a complement, not a substitute for prepared statements. if (!preg_match("/^[a-zA-Z0-9_]{3,20}$/", $username)) { die("Invalid username"); } Do not show SQL errors to the user: error messages can reveal the structure of your database. Log the detail and display a generic message: error_log($conn->error); echo "An error occurred.

Please try again."; // Limit database account permissions: not all database users need full access. A account that can only make SELECT and INSERT limits damage if something fails. Keep everything updated: PHP, the web server, and the database manager to patch known vulnerabilities. Conclusion To prevent SQL injection in PHP, always use prepared statements, validate input as a complement, do not show internal errors, and limit database permissions. For the complete example and detailed explanation, see the original article on Todo se Aprende.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

30,000+ downloads: what shipping 21 safe-by-default MCP servers taught me

The dockndevai MCP suite just crossed 30,000 downloads on npm: 30,185 across 21 servers, with about 8,000 a month still coming in. I also posted the announcement on LinkedIn .

  • 30,000+ downloads across 21 servers on npm
  • Servers adhere to single governance model
  • Default mode is read-only with strict security

More from Tuesday 10 November →