Databases Reference
In-Depth Information
// Limit the length of the string
$input = substr($input, 0, $maxlength);
// Escape semicolons and (if magic quotes are off) single and
// double quotes
if(get_magic_quotes_gpc())
$input = stripslashes($input);
$input = mysqli_real_escape_string($connection, $input);
return $input;
}
We can pass the input string and the maximum permissible length to the function, and
obtain the processed string as the return value, for example:
$username = clean($_POST["username"], 30);
Remember that there must be an active connection to the MySQL server for
mysqli_real_escape_string( ) to work, and so we must connect to the MySQL server
before we ever use the clean( ) function. On a high-volume application, you can avoid
unnecessary connections to the MySQL server by validating the input in two
steps. First, the script can perform simple checks that don't use
mysqli_real_escape_string( ) . Then, the script can connect to the MySQL server, es-
cape the input using mysqli_real_escape_string( ) , and then continue with other da-
tabase operations.
The global keyword tells PHP to use the $connection variable from outside the
clean( ) function; without it, PHP would create a new, completely different variable
with the name $connection that would be in effect inside the function, which would be
useless for our function. We could instead have defined the function as:
function clean($input, $maxlength, $connection)
{
...
}
so that the value of the $connection variable is passed to the function as part of the
function call, for example:
$username = clean($_POST["username"], 30, $connection);
Using Data from the Client
You should also be careful how you use data that is received from the browser. For
example, it is unwise to use the price of an item from a form widget to calculate an
invoice; even if the price is hidden or read-only, the user can still change it by modifying
the form or the URL. The correct approach is to verify the price against the database
before calculating the invoice. Similarly, don't embed SQL in HTML—even if it is
hidden—as the user can browse the HTML source, understand the database structure,
 
Search WWH ::




Custom Search