John Knowles - Development Blog

PHP/SQL Injection

Post by: John Knowles On 2006-12-13 14:02:41

It’s been a while since my last blog. I have had a lot of work with assignments and other project which I have been snowed under with.

The topic for today is SQL injection with PHP.

SQL injection is a big problem for everyone and if your using databases you will have to more than likely have to deal with it at some time in your life. You see it all the time when you go onto a website you always use and someone has left a message as the administrator saying they have the user database and full control of the forum. We as developers have a responsibility to prevent this were ever possible. There is no sure fire way to stop SQL injection as a good cracker will always find a way round your security measures.

This website runs mainly off an MySQL database. When I was rebuilding a while ago I reused a lot of code from my old website models which I had wrote. All of my old code was PHP 4 and needed updating (Which you will already know if you have read my previous blogs). By doing this many security threats which I was too naive and not technically minded enough to understand were taken away. I could have kick myself with some of the holes within my website even the navigation system left a large hole into my database. Without doing into too much depth about how my website is coded. (If people can’t see what there trying to crack it makes it a lot harder) I had my MySQL login as a full rights user which could drop tables and so on. This alone was a large threat. Then I notices I was passing RAW data from the url into an SQL query. I might have well just uploaded a form with a blank query connected to my database.

A few quick notes to finish:

+ Remember always process any data which you enter into a database.
+ Forms, urls are holes make sure you escape any queries which are entered into these.
+ Use REGEX and pattern matching to reduce the risk.
+ Add slashes to quotes
+ Always code defensively if theres a hole in your system the wrong person will find it