2012-04-09 152 views
0

我将表单元素保存到文件中,并且以下按预期工作。检查表单元素是否存在

$t_str .= "viewMandatory=".$_GET['viewMandatory'] ."\n"; 

但我需要的是,如果$ _GET设置,那么它应该被附加到“t_str”字符串。

如果未从窗体收到viewMandatory值,则不应该打印任何内容。如何将此检查添加到上述语句中?

+0

有[大量](http://stackoverflow.com/questions/3496971/check-if-post-exists)相似的](http://stackoverflow.com/questions/3432282/check-if-any-variables-are-passed-in-a-get)的问题,和[谷歌搜索非常成果](http:// www。 google.co.uk/webhp?#hl=en&output=search&sclient=psy-.ab&q=check+if+get+variable+exists&fp=1)。 – Alex 2012-04-09 07:16:56

回答

5
if (!empty($_GET['viewMandatory'])){ 
$t_str .= "viewMandatory=".$_GET['viewMandatory'] ."\n"; 
} 

在292个问题后,您应该遇到empty()函数。

+0

我想你缺少一个附加的'()'条件 – Joseph 2012-04-09 07:12:37

+0

谢谢@Joseph,傻我 – 2012-04-09 07:14:02

1
$t_str .= (!empty($_GET['viewMandatory'])?$_GET['viewMandatory']:null; 

这种方式,你有更少的代码,是什么使得它更易于阅读(至少对我来说,我喜欢短的形式),但代码将每次您请求的页面执行。 Dragon的解决方案并非如此。

但是想想代码注入。过滤$ _GET ['viewMandatory']之前,将其添加到您的字符串!否则,恶意代码可以被注入很简单,例如:

www.yourpage.com/page.php?viewMandatory=';BAD_CODE_HERE (or " instead of ') 
1
Use php isset  


if (isset($_GET['viewMandatory'])){ 
$t_str .= "viewMandatory=".$_GET['viewMandatory'] ."\n"; 
}