简体   繁体   English

页面从“#”作为GET参数崩溃

[英]Page crashing from '#' as a GET-parameter

Ive been using URL-parameters to make a landingpage behind a searchform more personal. 我一直在使用URL参数来使搜索表单后面的目标网页更加个性化。 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. 直到我尝试将?city =#之类的值用作值,然后我的整个页面崩溃了,我不再确定了。

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. PHP具有许多功能,可帮助您避免此类问题。
Whenever you create URL to be displayed in the browser it has to be urlencoded . 每当您创建要在浏览器中显示的URL时,都必须使用Urlencoded If you are just appending the query string part to a fixed url you can build that string with http_build_query . 如果您只是将查询字符串部分附加到固定的URL,则可以使用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. URL中的#表示URL的另一部分,即哈希部分。 This is not going to be a part of your $_GET superglobal. 这不会成为$_GET超全局变量的一部分。

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 . 如果出于任何原因您想手动输入带有#的查询字符串作为URL,那么您需要使用编码版本%23 eg http://php.net/manual-lookup.php?pattern=%23 例如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 . PHP对此已经有了一个扩展: filters

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM