At what layer can SQL injection happen?

Hello. I am learning about working with server-side data for websites. I’ve been researching sql injections, and methods used to avoid this such as prepared statements. But I have 2 questions which I’m not clear about.

  1. How is someone able to inject SQL into a query if they don’t have access to your PHP files where you wrote the queries?

  2. PHP is processed on the server. So if no-one can view the page source via http, why is it necessary to hide db-connect information in a PHP script? Assuming you’re the only db admin.

I would really like to understand these two things and am grateful for your advice.

Injection occurs when the data someone enters gets misinterpreted as SQL. If you keep the SQL and data separate by using a prepare statement for the SQL and then bind the data to it in a separate statement injection cannot occur.

If you validate (or at least sanitize) all of the data inputs so that they all make sense for what they are supposed to contain then only those fields that can look like SQL would be able to be used to even attempt injection.

Where the data can’t be kept separate from the code (as used to be the case with the now dead mysql_ interface) you needed to escape any fields that could contain characters that would allow the data and SQL to be confused in order to not break the SQL (or allow injection).

If PHP is off on the server for any reason (perhaps it crashed) then any PHP pages will be displayed as if they were text files. Any db-connection information would then be readable to everyone.

Your statement that no-one can ead the source via HTTP is only true while the page is interpreted as PHP and becomes untrue as soon as PHP crashes.

The process of applying ALL of these measures on top of one another even though some will be unnecessary because a prior measure should have already prevented the problem and others are covering extremely unlikely situations is called DEFENSE IN DEPTH. If one layer of security fails or is successfully bypassed then they still can’t get in because of all of the subsequent security measures that still apply.

2 Likes

Thanks for clarifying that.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.