Databases Reference
In-Depth Information
The PHP substr( ) function returns a specified portion of a string. You can limit the
data passed from a form using this function; for example, you can choose to use just
the first 15 characters:
// Reduce the length of the artist name to at most 15 characters
$_GET["artist"] = substr($_GET["artist"], 0, 15);
The 0 indicates that the returned substring should start from the initial character (char-
acter 0), and the 15 specifies the maximum number of characters to be returned.
Before processing input data, you should check that some data has in fact been passed
to you:
// Check that an artist name has been passed to us
if(empty($_GET["artist"]))
die("You should have entered an artist name.");
When data has a specific type, you should consider adding extra steps in the validation
process. For example, suppose you're expecting a user to type in a currency amount in
dollars and cents, and this is available as $_GET["money"] in your script. You can validate
it by checking that the data isn't longer than expected and also that it contains only
digits and period characters. There are many ways to do this, but let's use one with the
techniques we've shown in this chapter:
$len = strlen($_GET["money"]);
for($x=0; $x&<$len; $x++)
{
if (
(
($_GET["money"][$x] < "0" || $_GET["money"][$x] > "9")
&&
($_GET["money"][$x] != ".")
)
||
($x > 6)
)
die("Invalid parameter: {$_GET["money"]}");
}
The strlen( ) function is a string library function that reports the length of a string as
an integer value. The for loop goes through each character in the input, which is ac-
cessed as $_GET["money"][$x] . If the character is less than 0 or greater than 9 and isn't
a period character, an error is generated. Also, if the loop is repeated more than six
times, an error is generated because the input is too long.
Another common way to validate data is to use regular expressions; we won't go into
the detail of that approach here.
 
Search WWH ::




Custom Search