Forum Moderators: coopster

Message Too Old, No Replies

Using preg match in my script

Need help!

         

spyder_tek

3:20 am on Dec 22, 2006 (gmt 0)

10+ Year Member



Below is a script that passes data to a from with a URL, using for example: [www,site,com...]


<?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!

Psychopsia

4:00 am on Dec 22, 2006 (gmt 0)

10+ Year Member



A solution to implement regular expressions could be:

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]

eelixduppy

4:41 am on Dec 22, 2006 (gmt 0)



Then the patterns would be something like this, although you are going to have to fix your function because you want two different checks, not just one for all variables:

$pattern1 = "/^([\d\.\$])+$/"; //allows for numbers, period, dollar sign

and...

$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.

Psychopsia

4:54 am on Dec 22, 2006 (gmt 0)

10+ Year Member



not asserting the start and end of the subject using ^ and $ respectively.

Yep, you're right! I forget it

spyder_tek

12:11 am on Dec 23, 2006 (gmt 0)

10+ Year Member



Thank you! You helped steer me in the right direction. ;)