Need help with preg_match against simple string

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
erika
Forum Newbie
Posts: 17
Joined: Sat Oct 25, 2008 5:27 pm

Need help with preg_match against simple string

Post by erika »

preg_match is the bane of my existence, I just don't get it. :banghead: I am using mod_rewrite to create SEO-friendly URLs and would like to minimize the security hole presented with $_GET by checking to ensure that contents include only alphanumeric characters, spaces, hyphens, and underscores.

I am passing restaurant types which include, for example:

Pizza
Other - Dining
Cajun/Creole

On the linking page I am re-writing the above to:

Pizza
Other%20-%20Dining
Cajun_Creole

The data I get is exactly what I sent, except for the %20s, which turn back into spaces.

So I thought I could do something like this:

Code: Select all

	$category = $_GET['category'];

	$good_chars = '/[a-zA-Z0-9]/';

	if (preg_match($good_chars,$category)) {

		print $category . " has bad characters in it.";
	}

	else {

		print $category . " has no bad characters.";
	}
But that results in 100% rejection of the strings.

I thought maybe I had it backwards, so I put a ! in front of preg_match, but that resulted in 100% acceptance of the strings.

I'm obviously missing something and I don't know what... knowing WHY would be even more helpful.

Any assistance at all is greatly appreciated.
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Need help with preg_match against simple string

Post by cpetercarter »

You need to tell the regex engine that anything between the beginning of the string (^) and the end ($) should be an alphanumeric character ([a-zA-Z0-9]) and that there may be one or more of them (+).

Code: Select all

$good_chars = '/^[a-zA-Z0-9]+$/';
erika
Forum Newbie
Posts: 17
Joined: Sat Oct 25, 2008 5:27 pm

Re: Need help with preg_match against simple string

Post by erika »

Thank you, that's exactly what I needed! :)
Post Reply