Home » Php » php – Better way for checking $_REQUEST variable

php – Better way for checking $_REQUEST variable

Posted by: admin July 12, 2020 Leave a comment

Questions:
$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 ?

How to&Answers:

Create your own function :

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

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

There’s no other clean solution.

Answer:

How more shorter do you want it?

Of course, if you are using this every time 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:

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

Answer:

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

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

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

Answer:

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

$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_NOTICE along the lines of “undefined index“.

Answer:

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.

/**
 * 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;
}

Answer:

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

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; 
} 

Answer:

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.

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.

Answer:

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.

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;