PHP Magic Quotes
You can use a HTML form to query your databases. But there are special security considerations you need to bear in mind. We'll look at those issues in this section.
If you use things like text boxes and text areas on your forms, you need to
take care. This is because of an attacks like SQL injection. Things like single
quotes need to be escaped. But you can use an inbuilt PHP function for this:
mysql_real_escape_string( )
We'll see how this works in a moment, but let's get some practical work done. There is a file amongst the ones you downloaded called magicTest.php (in the scripts folder). Load this script in your browser, with your server running. You should see a text box and a button. Typed the following name into the text box:
O'Connor
Now click the button. You should see the name printed exactly as it is in the text box.
So far, so good. Now, try this.
When you installed your server, there will be a file called php.ini. This is a list of all the various settings to do with PHP itself. Locate this file called php.ini (in the folder called apache, or do a search for it). Open it up in a text editor. Search for this line:
magic_quotes_gpc = Off
Change the Off to On, if it's not already on. Then save the changes.
Now load up the your PHP script with the text box and the button. With O'Connor still in the text box, click your button again. You should see this printed:
O \' Connor
So PHP has put a backslash before the single quote. But what's going on?
Characters like single and double quotes can be very dangerous, if you're running SQL on your databases tables. These characters can be used to launch a SQL injection attack. So the makers of PHP came up with a function called magic_quotes_gpc. If this is set to On, then PHP will add the backslash to all single and double quotes. That way, an attacker's life is made more difficult. As an example, we'll load up a database and a script. These are already prepared for you.
Amongst the files you downloaded there is a folder called databases. Inside this folder there is a one called membertest. Save the entire membertest folder to your data directory in your mysql data folder. For Wampserver users this will be at:
C:\wamp\bin\mysql\mysql5.5.8\data
(If you have an earlier or later version, the number will be different.)
Now set magic_quotes_gpc = On back to magic_quotes_gpc = Off in your php.ini file.
Along with the database folder there is a PHP script called magicTest2.php (in the scripts folder). We'll use this script, and the database, to teach you about SQL injection. Not so that you can launch your own attacks, of course! It's so that you can thwart them.