MySQL PHP Security

Authored by Corey Ballou

1 Comment

Escaping MySQL ‘LIKE’ Queries in PHP

Unlike most common MySQL escaping scenarios in PHP, one needs to take extra precautionary measures when implementing a LIKE query. LIKE queries contain special qualifiers for term matching, % and _, which the user could maliciously include in their search terms. These qualifiers enable matching of 0 or more characters and any single character, respectively. MySQL’s own escape function as well as PHP’s magic quotes setting ignores LIKE qualifiers. For this reason, user’s can abuse insecure systems by complicating LIKE matching, perhaps skipping indexing by prefixing a % or _. This could effectively lead to a Denial of Service (DoS) attack by overloading a decently sized database.

Example Attack

An example attack is as easy as a user inputting data with a prefix of % or _:

The Fix

Since both % and _ are both common operators, users could unknowingly compromise your system as well. To address this LIKE security flaw, we need to implement a custom escaping mechanism for the two special qualifiers:

We use addcslashes() because it functions much the same as addslashes() and is a much faster alternative to str_replace() or a regular expression.

Author: Corey Ballou

Corey Ballou is the CEO of Whether you're a student, young professional, entrepreneur, startup, or small business, you can be up and online fast with your own custom domain, email, and webpage on POP. Corey is a professional PHP developer by trade, specializing in custom web applications development for startups, small businesses, and agencies. Follow Corey on Twitter @cballou.

  • Guru