Jump to content

preg_match problem


Tom10
Go to solution Solved by Psycho,

Recommended Posts

Hey i am trying to use preg_match with my website URL

$url = "".$_SERVER['SERVER_NAME']."".$_SERVER['REQUEST_URI']."";

if(preg_match('#([\^A-Za-z0-9\$]#', $url)) {



} else {

	die("<h1>Security error</h1>");

}

I want to kill the page and say "Security Error" if a client tries to inject code into the url, but i can't get this to work.

 

All help is very much appreciated :),

 

Thanks

Link to comment
Share on other sites

So, what are you considering malicious code? I.e. what code are you wanting to allow vs code you don't want to allow?

I am wanting to block out javascript attacks like

index.php?=<script>onload=alert(document.cookie);</script>

It's mainly i'm wondering how to detect using preg match if someone has entered this code or something similar

Link to comment
Share on other sites

  • Solution

Characters like < get encoded to something like '%3C'. So, they wouldn't be caught in a preg_match check. You need to be sure to not convert them back to their native characters. But, this should work for what you described:

$fullURL = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . '';
echo "Full URL: {$fullURL}<br>";
 
if(preg_match("#[^\w\/\?\&\.\=]#", $fullURL))
{
    echo "Security error";
}
else
{
    echo "URL OK";
}

That regex covers:

 

\w = a-z, A-Z, 0-9 & _ (underscore)

/ (forwardslash)

? (question mark)

& (ampersand)

. (period)

= (equals sign)

Edited by Psycho
  • Like 1
Link to comment
Share on other sites

Characters like < get encoded to something like '%3C'. So, they wouldn't be caught in a preg_match check. You need to be sure to not convert them back to their native characters. But, this should work for what you described:

$fullURL = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . '';
echo "Full URL: {$fullURL}<br>";
 
if(preg_match("#[^\w\/\?\&\.\=]#", $fullURL))
{
    echo "Security error";
}
else
{
    echo "URL OK";
}

That regex covers:

 

\w = a-z, A-Z, 0-9 & _ (underscore)

/ (forwardslash)

? (question mark)

& (ampersand)

. (period)

= (equals sign)

Worked like a charm mate thank you so much :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.