This is far from best practice, but I just saw a piece of code that I found very interesting to say the least. The code was executing some SQL, and it was not using prepared statements so it is wide open for SQL injection.

It did however have an unorthodox approach to this. It is "secure" because all input parameters are limited to 2 characters long. And this got me thinking: is there any way an attacker can exploit this? I will of course change the code to use prepared statements, but still, I am quite curious


2 Answers 2


It does reduce the possibility/magnitude of harm caused by SQL injection, but definitely does NOT make your application secure against it.

For example, say your field takes 2 character input, and the server runs a LIKE operation on the input. Say the user enters something like A*, which satisfies the 2-character limit, but this would result into all the records starting with character A, and depending upon the scenario, the user might have access to data which he's not supposed to.

Hence, input validation should always be done immediately after accepting the input, as well as before sending it to the user.

  • I didn't think about the LIKE scenario, so good point. In this specific case though it is matching explicity like this " AND field = '" + field + "'" which I guess makes it even harder to exploit.
    – munHunger
    Commented Mar 22, 2018 at 13:29

There are tons of resources available on the best practices of taking input parameters and I have never seen only limiting the character length as a viable or secure option. So yes, a attacker can exploit this. After all, you are already open to SQL injection so you can't be sure of the possible attacks and limiting the length surely does not help you sleep. Usually if you aren't using prepared statements, you have a whitelist of inputs or a specific criteria of the inputs you accept. If the supplied input does not match, you throw a error. Checking the length of a input is fine, but it should not be the only defense but rather a additional restraint in your application.

For example, an attacker might use " or ""="as a possible injection attack. While this is longer than 2 characters, you can see there are many different ways to do this and I'm sure some are 2 characters.

Not the answer you're looking for? Browse other questions tagged .