There are also other ways of sanitising input, and a very useful one is typecasting. Taking another SQL example, say we were allowing the users to specify an offset to display data. In a query something like this:
<?php
// code...
$sql = 'SELECT id,title FROM news LIMIT '.$_GET['offset'].',10';
$result = mysql_query($sql);
// more code...
?>
We could use the same function as before to sanitise this $_GET variable, but it is more appropriate to use typecasting to force it to be an integer. We can do this using intval(). Intval takes a variable, and returns its value as an integer. So, a string "14" will become the number 14, and any input that is not numeric will become 0, making the input safe to work with.
<?php
// code...
$sql = 'SELECT id,title FROM news LIMIT '.intval($_GET['offset']).',10'; // sanitised input
$result = mysql_query($sql);
// more code...
?>
An important thing to remember about sanitisation, is that it is not just required only when inputing data into something like a database! Outputting an unsanitised variable can be just as dangerous as taking it as input for another purpose. For example, say we had a simple script that took a $_GET variable called "name", then output "Hello, [name]!". If you do not sanitise the user input then a user can craft a malicious URL to your script that will send cookies associated with your domain to them. How could they do that? By placing HTML code in the URL which executes some Javascript when the page is loaded.
<?php
// Dangerous! $_GET['name'] has not been sanitised.
echo 'Hello, ',$_GET['name'],'!';
?>
Now we know what the vulnerability, how can we stop it? Luckily PHP provides a very useful function for just this purpose, called htmlspecialchars(). This function replaces possibly dangerous characters like < with their HTML Entities. In the case of < it would become <. Below we can see htmlspecialchars in use, sanitising out user input to make the script safe.
<?php
// This is now safe because the user input has been sanitised.
echo 'Hello, ',htmlspecialchars($_GET['name'], ENT_QUOTES),'!';
?>