Fix SQL Injection (Legacy & Modern) in Symfony
SQLi in Symfony isn't dead; it just evolved. Whether you're rocking legacy DBAL or modern Doctrine DQL, string concatenation is your funeral. Stop building queries like it's 2005. Real pros use parameter binding to neutralize the payload before it hits the engine. This guide covers how to kill SQLi at the source using Doctrine's built-in protections.
The Vulnerable Pattern
// 1. Legacy DBAL Raw SQL Injection $conn = $this->getEntityManager()->getConnection(); $sql = "SELECT * FROM users WHERE email = '" . $_GET['email'] . "'"; $stmt = $conn->prepare($sql); // Vulnerable: string concatenation
// 2. Modern DQL Injection $query = $em->createQuery(“SELECT u FROM App\Entity\User u WHERE u.id = ” . $id); // Vulnerable: DQL is not immune to concatenation
The Secure Implementation
The vulnerability stems from treating untrusted input as executable code. In the vulnerable examples, an attacker can escape the string literal and append 'OR 1=1' to bypass authentication or dump the database. The secure examples leverage Prepared Statements. By using '?' or ':id' placeholders, the SQL structure is sent to the database separately from the data. The database engine treats the parameters strictly as data, never as executable SQL commands. For dynamic identifiers like table or column names which cannot be bound, you must use a strict whitelist of allowed strings.
// 1. Secure DBAL with Positional Placeholders $conn->executeQuery('SELECT * FROM users WHERE email = ?', [$email]);// 2. Secure DQL with Named Parameters $query = $em->createQuery(‘SELECT u FROM App\Entity\User u WHERE u.id = :id’) ->setParameter(‘id’, $id);
// 3. The Modern Standard: Query Builder $qb = $this->repository->createQueryBuilder(‘u’) ->where(‘u.email = :email’) ->setParameter(‘email’, $email) ->getQuery();
Your Symfony API
might be exposed to SQL Injection (Legacy & Modern)
74% of Symfony apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.