Simple clear advice in plain English

Hands on: SQL injections

Prevent SQL injections with the help of PHP

The result? If there’s a table called users, with a username and email column, they’ll get a handy list of users, followed by a colon and then their email address. So, how can you stop this happening?

First, always validate data before feeding it straight into a database query. The basic protection added to a script by Dreamweaver isn’t enough. If there are only certain values that can be used for the category, check for them.

And if the only possible values are numeric, use that to your advantage. PHP contains a function called is_numeric, which you can use to check if it really is just a number you’ve got, or you can use intval to extract the numeric part of a string. Either would protect your script.

To see what people are trying to do to your server, add a short snippet of code like this, before the query:
if ( isset($_GET[‘catid’]) && ! is_numeric($_GET[‘catid’])) {

// send an email to admin
$errbody = sprintf(“A script was called with invalid parameters\nRequested URL: %s\nOriginating IP: %s\nQuery string: %s\nReferrer: %s\n”,

$_SERVER[‘REQUEST_URI’], $_SERVER[‘REMOTE_ADDR’], $_SERVER[‘QUERY_STRING’], 4 $_SERVER[‘HTTP_REFERER’]) ;
mail(‘admin@mysite.com’, ’Script error’,$errbody) ;
header(‘Location: /index-error.php’) ;
exit ;
}

This will redirect the visitor to the page index-error.php, where you can issue dire warnings, or just say, “Sorry, you typed something wrong.”
Obviously, you can’t use such a simple check if catid can be a range of words; instead, you would need to use something like this:
( $_GET[‘catid’] != ‘brakes’ ) && ( $_GET[‘catid’] != ‘fuel’)

Reader Comments

   

Add your comment

All fields must be completed. Your email address will not be displayed or used to send marketing messages.

All messages will be checked by moderators before appearing on the site.

See our Privacy Policy for more information.

Related articles

Hands on: Foreign characters

Dealing with letters that have accents and diacritical marks in assorted languages

How to use Perl or PHP scripts on your web site

Automate tasks and improve ease of use when processing data on the web

Question & Answer

Q.Why are some of the keys on my keyboard doing strange...

> Read the answer

Q.Is my phone’s Bluetooth any use?

> Read the answer

Q.Can I switch boot drives so that I can work on older...

> Read the answer

Best deals on the web

img

Samsung RV520-A07

£359.98- Buy it now

img

Acer Aspire 5750G (LX.RXP02.019)

£399.99- Buy it now

img

Apple MacBook Pro (MD313B/A)

£904.37- Buy it now

Latest issue & subscription deals

Poll

Are you concerned about viruses that target mobile phones?

Jargon Buster

Computing terms explained in plain English

CAD

Computer Aided Design. Software used to create 3D models.

Great shopping deals from Computeractive