Forum Moderators: coopster
<?php
function getIt($value){
if($_GET[$value]){
return $_GET[$value];
}else{
return "";
}
}?> <input type="text" name="price" value="<?php echo getIt("price")?>">
<input type="text" name="title" value="<?php echo getIt("title")?>">
I'm still learning PHP, so my question is this...
I want to validate my input using preg_match, (I'm assuming this would be the easiest and most secure method).
How can I modify my script so that preg_match:
ONLY accepts numbers, dollar signs and periods from:
<input type="text" name="price" value="<?php echo getIt("price")?>">
and ONLY accepts values containing letters and numbers from:
<input type="text" name="title" value="<?php echo getIt("title")?>">
Finally, how can I modify my script so that preg_match checks "price" and "title" before passing the data from the URL to my form, and if any invalid characters are found the script stops?
Thanks!
function getIt($key, $regex)
{
if (isset($_GET[$key]) &&!empty($_GET[$key]) && preg_match('#' . $regex . '#is', $_GET[$key]))
{
return trim($_GET[$key]);
}
return false;
}
$price = getIt('price', '[0-9\.\$]+');
$title = getIt('title', '[a-zA-Z0-9]+');
if (getIt('price', '[0-9\.\$]+') === false)
{
// Incorrect value
}
[edited by: Psychopsia at 4:03 am (utc) on Dec. 22, 2006]
$pattern1 = "/^([\d\.\$])+$/"; //allows for numbers, period, dollar sign
$pattern = "/^([\w])+$/"; //allows for alphanumerics and the underscore
Flag this thread [webmasterworld.com]. :)
The problem with Psychopsia's pattern was that it wasn't making sure that the string ONLY contained those values by not asserting the start and end of the subject using ^ and $ respectively.