php 检查 $_REQUEST 变量的更好方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12933550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:30:10  来源:igfitidea点击:

Better way for checking $_REQUEST variable

phprequest

提问by Champ

$p = (isset($_REQUEST["p"])?$_REQUEST["p"]:"");

This is the common line I usually use in my php code. I always assume is there a better(small and faster) way to write the same ?

这是我通常在我的 php 代码中使用的常用行。我总是假设有更好的(小而快的)方法来写同样的东西吗?

回答by Aelios

Create your own function :

创建自己的函数:

function getIfSet(&$value, $default = null)
{
    return isset($value) ? $value : $default;
}

$p = getIfSet($_REQUEST['p']);

There's no other clean solution.

没有其他干净的解决方案。

回答by Peon

How more shorter do you want it?

你想要多短?

Of course, if you are using this everytime you access a request value, you should create a function somewhere and then use that:

当然,如果每次访问请求值时都使用它,则应该在某处创建一个函数,然后使用它:

function reqVal( $val, $default = "", $no_sql = true )
{
    $var = isset( $_REQUEST[$val] ) ? $_REQUEST[$val] : $default;
    $var = $no_sql ? nosql( $var ) : $var;
    return $var;
}

function getVal( $val, $default = "", $no_sql = true )
{
    $var = isset( $_GET[$val] ) ? $_GET[$val] : $default;
    $var = $no_sql ? nosql( $var ) : $var;
    return $var;
}

function postVal( $val, $default = "", $no_sql = true )
{
    $var = isset( $_POST[$val] ) ? $_POST[$val] : $default;
    $var = $no_sql ? nosql( $var ) : $var;
    return $var;
}

Now add the sql incjection check:

现在添加 sql 注入检查:

function nosql( $var )
{
    if ( is_array( $var ) ) {
        foreach ( $var as $key => $elem ) $var[$key] = nosql( $elem );
    } else if ( $var === null ) {
        return null;
    } else {
        if ( get_magic_quotes_gpc() ) $var = stripslashes( $var );
        $var = mysql_real_escape_string( $var );
    }
    return $var;
}

And access it always simple like this:

访问它总是像这样简单:

$p = reqVal( 'p', 0 );
$p = getVal( 'p', 'something', false );
$p = postVal( 'p' ); // or just forget the 2nd and 3rd parameter

回答by fbas

EDIT: PHP 7 adds a null coalescing operator ("??")

编辑:PHP 7 添加了一个空合并运算符(“??”)

$p = $_REQUEST["p"] ?? '';

https://www.php.net/manual/en/migration70.new-features.php

https://www.php.net/manual/en/migration70.new-features.php



ORIGINAL:

原来的:

if you want something shorter, and are content with an empty (string) default value, the following works:

如果你想要更短的东西,并且满足于一个空的(字符串)默认值,下面的工作:

$p = @$_REQUEST['p'];

@ is the error-suppression operator and will keep the expression from giving a warning if the value is not set.

@ 是错误抑制运算符,如果未设置该值,它将阻止表达式发出警告。

http://www.php.net/manual/en/language.operators.errorcontrol.php

http://www.php.net/manual/en/language.operators.errorcontrol.php

回答by Victor Stanciu

I usually take advantage of the fact that PHP is loosely typed and simply do:

我通常利用 PHP 是松散类型的这一事实,然后简单地执行以下操作:

$p = (string) $_REQUEST['p'];

This way, even if $_REQUEST['p']is not set, an empty string still gets stored into $p. Keep in mind that this only works if your error handler ignores notices, as accessing an unset key will trigger an E_NOTICEalong the lines of "undefined index".

这样,即使$_REQUEST['p']未设置,空字符串仍会存储到$p. 请记住,这仅在您的错误处理程序忽略通知时才有效,因为访问未设置的键将触发E_NOTICEundefined index”。

回答by martinstoeckli

This is indeed so common, that i wonder there is no native way of doing it in PHP. Most developers write their own function to read safely from an array.

这确实很常见,以至于我想知道在 PHP 中没有本地方法可以做到这一点。大多数开发人员编写自己的函数来安全地从数组中读取。

/**
 * Gets the value associated with the specified key from an array.
 * @param array $array The array to search for the key.
 * @param mixed $key The key of the value to get.
 * @param mixed $default The default value to return, if the
 *   specified key does not exist.
 * @return mixed Value that is associated with the specified
 *   key, or the default value, if no such key exists.
 */
function getValueFromArray($array, $key, $default = null)
{
  $containsKey = isset($array[$key]);
  if ($containsKey)
    return $array[$key];
  else
    return $default;
}

/**
 * Gets the value associated with the specified key from an array.
 * @param array $array The array to search for the key.
 * @param mixed $key The key of the value to get.
 * @param mixed $value Retrieves the found value, or is set to null
 *   if the key could not be found.
 * @return bool Returns true if the key could be found, otherwise false.
 */
public function tryGetValueFromArray($array, $key, &$value)
{
  $containsKey = isset($array[$key]);
  if ($containsKey)
    $value = $array[$key];
  else
    $value = null;
  return $containsKey;
}

回答by Bogdan Burym

You can find many examples of different solutions here http://php.net/manual/en/function.isset.phpin the User Contributed Notessection.

您可以在http://php.net/manual/en/function.isset.phpUser Contributed Notes部分找到许多不同解决方案的示例。

Try this:

尝试这个:

function get_if_set( $varname, $parent=null ) { 
    if ( !is_array( $parent ) && !is_object($parent) ) { 
        $parent = $GLOBALS; 
    }
    return array_key_exists( $varname, $parent ) ? $parent[$varname] : null; 
} 

回答by SDC

The answers that wrap your existing code in a function are good - they do indeed tidy up the code if you've got a bunch of them.

将现有代码包装在函数中的答案很好 - 如果您有一堆代码,它们确实可以整理代码。

However the better solution is to sanitize your entire request array based on a set of expected values before you start.

然而,更好的解决方案是在开始之前根据一组预期值清理整个请求数组。

For example:

例如:

function sanitiseRequest() {
    $expected = array(
        'p' => '',
        'id' => 0,
        //etc
    );

    //throw away any input that wasn't expected...
    foreach($_REQUEST as $key=>$value) {
        if(!isset($expected[$key]) { unset $_REQUEST[$key]; }
    }
    //and for any expected values that weren't passed, set them to the defaults.
    foreach($expected as $key=>$defvalue) {
        if(!isset($_REQUEST[$key]) { $_REQUEST[$key] = $defvalue; }
    }
}

Then simply add a call to this function at the start of the code, and you won't need to worry about doing isset($_REQUEST[..])anywhere else in your code.

然后只需在代码的开头添加对该函数的调用,您就无需担心isset($_REQUEST[..])在代码中的任何其他地方执行任何操作。

This concept can be expanded to force the incoming arguments to be the correct data type as well, or any other data cleansing you may want to do. This can give you complete confidence that the incoming data is populated as you expect.

可以扩展此概念以强制传入参数也为正确的数据类型,或者您可能想要执行的任何其他数据清理。这可以让您完全相信传入的数据已按预期填充。

Hope that helps.

希望有帮助。

回答by bokan

This one works well for me. And you don't have to write the name twice. It won't change the var if it is already set. So it is safe to use for quick n dirty conversion of old application using register_globals.

这个对我来说效果很好。而且你不必写两次名字。如果它已经设置,它不会改变 var。因此,使用 register_globals 对旧应用程序进行快速 n 脏转换是安全的。

function getIfSet($key, $default = null)
{
    global $$key;

    if(!isset($$key)){
        if(isset($_REQUEST[$key])){
            $$key=$_REQUEST[$key];
        }else{
            if(!is_null($default)){
                $$key = $default;
            }
        }
    }
}
function getIfSetArray($list){
    foreach($list as $item){
        getIfSet($item);
    }
}

getIfSet('varname');
getIfSetArray(['varname_1','varname_2']);

echo $varname;
echo $varname_1;