Ive been using URL-parameters to make a landingpage behind a searchform more personal. I felt relatively bulletproof validating stuff like this
$string = $_GET['city']
$res = preg_replace("/[^a-zA-Z0-9]/", "", $string);
until I tried something like ?city=# as a value and my whole page crashed and im not so sure anymore.
What is the way to go to validate without writing a whole engine or at least stop my page crashing from #?
Thanks
PHP has a lot of functionalities which help you avoid problems like this.
Whenever you create URL to be displayed in the browser it has to be urlencoded . If you are just appending the query string part to a fixed url you can build that string with http_build_query . For example:
$querystring = [
'param1' = 123,
'param2' = 'hello with a #'
];
$QS_encoded = http_build_query($querystring);
echo '<a href="?'.$QS_encoded.'">My link</a>';
#
in URL denotes another part of URL which is the hash part. This is not going to be a part of your $_GET
superglobal.
If for any reason you would like to type out the URL with a query string containing #
manually by hand, then you need to use the encoded version %23
. eg http://php.net/manual-lookup.php?pattern=%23
On a side note. You shouldn't use regex for filtering data like this. PHP once again has already an extension for this: filters .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.