Reputation: 13
I just transferred a PHP website from a Linux server to Windows. Everything seems to function the same except one huge difference:
On the Linux server, the following piece of code is ignored when $_GET['action']
is not set:
$action = $_GET['action'];
if($action=='add'){
echo 'good';
}
However, this prevents the page from loading on the Windows server.
What does work is:
if(isset($_GET['action'])){
$action = $_GET['action'];
}else{
$action='';
}
if($action=='add'){
echo 'good';
}
2 questions:
Is there a way to configure the server to be more forgiving of variables that don't have a value?
Is the second code example better practice?
Upvotes: 1
Views: 62
Reputation: 4433
In my opinion, it's definitely better practice to check whether an array index or variable is set, and to keep your error reporting conservatively verbose.
For ease of working with data and to avoid cluttering my code with ternaries every time this situation can come up (often, if you use PHP arrays to hold optional configuration data but want to embed reasonable defaults in your code), I have always found it constructive to have an array extraction function tucked away in my core utilities code, as follows:
function aex( &$srcArray, $variableName, $defaultValue = null )
{
return isset( $srcArray[$variableName] )
? $srcArray[$variableName]
: $defaultValue
;
}
So then you'd just extract your variable like this:
$action = aex( $_GET, 'action', 'none' );
And it will be guaranteed to have a useful value and not to throw a warning.
Upvotes: 0
Reputation: 175038
The second server is merely configured to display errors by default, whereas the first one does not.
If you place the following piece of code at the top of your page, it will show the notice on the first server as well:
error_reporting(E_ALL);
Checking if the variable exist is always a good practice.
Upvotes: 2
Reputation: 25753
Is there a way to configure the server to be more forgiving of variables that don't have a value?
putting an @
symbol infront of the variable will tell php to ignore the error. but i consider this as bad practice.
Is the second code example better practice?
i do consider it as a good practice, it is always good to check.
IMO you should go for second, you can always use a ternary operator. so instead of
if(isset($_GET['action'])){
$action = $_GET['action'];
}else{
$action='';
}
you can write
$action = isset($_GET['action']) ? $_GET['action'] : '';
both does the same thing.
Upvotes: 3