$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 ?
$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 ?
Create your own function :
function getIfSet(&$value, $default = null)
{
return isset($value) ? $value : $default;
}
$p = getIfSet($_REQUEST['p']);
There's no other clean solution.
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
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
default value
parameter just like on Aelios' answer.
$default
is Aelios' property ;) I give it to you Dainis Abols
dot
but not with a comma
. Couldn't edit it because the fixing is very short. :)
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.
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
".
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;
}
getValueFromArray($_REQUEST, 'p')
. There is no native function as far as i know.
Commented
Oct 17, 2012 at 12:03
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;
}
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;