Tom10 Posted February 13, 2015 Share Posted February 13, 2015 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 Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 13, 2015 Share Posted February 13, 2015 So, what are you considering malicious code? I.e. what code are you wanting to allow vs code you don't want to allow? Quote Link to comment Share on other sites More sharing options...
Tom10 Posted February 13, 2015 Author Share Posted February 13, 2015 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 Quote Link to comment Share on other sites More sharing options...
Solution Psycho Posted February 13, 2015 Solution Share Posted February 13, 2015 (edited) 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 February 13, 2015 by Psycho 1 Quote Link to comment Share on other sites More sharing options...
Tom10 Posted February 13, 2015 Author Share Posted February 13, 2015 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.