H3XED

PHP: Avoid Using Undefined Variables and Indexes

Apr 5, 2012   Programming   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
PHP is a fairly loose programming language, which causes many new developers (and experienced ones) to get lazy. If you suppress errors, you can get away with ridiculous things like using undefined variables, without anyone being the wiser. But just because you can get away with it, doesn't mean you should.


Using undefined variables


Take this example:

<html>
<body>

Hello <?php echo $_GET['name']; ?>! You have been here <?php echo $_COOKIE['count']; ?> times!

</body>
</html>

What happens if $_GET['name'] doesn't exist? With error displaying and logging off, it will echo nothing, but if you migrate to a server that has display_errors on, you'll be in for a nice surprise.

It's good practice to define all variables that your script is going to use. I generally define mine at the top:

<?php

isset($_GET['name']) ? $name = $_GET['name'] : $name = 'Guest';
isset($_COOKIE['count']) ? $count = $_COOKIE['count'] : $count = '0';

?><html>
<body>

Hello <?php echo $name; ?>! You have been here <?php echo $count; ?> times!

</body>
</html>

That way you'll also have nice fallback values to use in the event of an unset variable or index. If you're wondering, those are ternary condition checks at the top.



Assuming a variable exists


Don't take for granted the existence of variables or array indexes. It is easy to do, for example with mysql functions. It might work 10,000 times, but that one time it doesn't, you might give away vital database or script information in an error message:

$q = mysql_query('SELECT ham FROM sandwich');
$r = mysql_fetch_assoc($q);
echo $r['ham'];

How about we add some validation in there? A little redundancy never hurt anyone either:

$q = mysql_query('SELECT ham FROM sandwich');

if($q == false || mysql_error() != '') exit(); // Check if mysql_query failed
if(mysql_num_rows($q) < 1) exit(); // Make sure some rows were returned

$r = mysql_fetch_assoc($q);

if($r == false || mysql_error() != '') exit(); // Check if mysql_fetch_assoc failed

if(isset($r['ham'])) $ham = $r['ham']; // Make sure row exists
else $ham = 'No ham :('; // Fallback value

echo $ham;

That's better. You probably don't want to just "exit" on an error, but you get the idea.
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter