B2B: Testing and defining variables in PHP


PHP is a dynamic, weakly-typed language, and as such, beginners to the language will often find their code acting unpredictably because of assumptions they have made.

PHP has a fairly low entry point for new programmers - it’s easy enough to get a couple of small sample scripts up and running, but on the same token, it’s really easy to pick up bad habits and carry them through into larger projects. Since PHP is often the first language used extensively by a new generation of web programmers, and doesn’t have strict typing or error reporting, a lot of people simply never pick up the best practices for system design and implementation.

This tutorial is going to be a quick introduction to variables in PHP, and how to test them effectively for missing or incorrect data.

To define a variable in PHP, you simply refer to it and assign it a value. Notice that you don’t need to place a type before it, e.g. int or string.

  $var1 = 'abc';

One variable is now present in your system, $var1, with the value abc.

If you are planning on using a group of variables in your program, it is generally good practice to declare them near the top of your function or method, or near the top of the file, and assign them sensible default values:

  $counter = 0;
  $name = '';
  $max = 10;

Testing variables

To maintain a predictable system, you need to ensure that you are always testing variables for expected values and sanitising them where necessary. Sanitising refers to cleaning up any data that has come from an untrusted source, i.e. a user submitted form or something similar. Such data must never be used directly without being checked or parsed - a common mistake is to take data a user has submitted and immediately use it in a database query:

  $query = "SELECT * FROM table WHERE name LIKE = {$_POST['name']}";

This is a classic example of an SQL injection flaw. A malicious user could easily craft a request to modify or even drop your entire database.

A better query would look like this:

  $name = mysql_escape_string($_POST['name']);
  $query = "SELECT * FROM table WHERE name LIKE = '$name'";

Notice the additional quotes around $name in the query; and the curly braces around the variable are no longer required as it isn’t a value being accessed in an array. Additionally, notice that the $query string is surrounded by double quotes (”) - this means that variables and string literals inside the string will be parsed.

  $name = 'Michael';
  $test1 = 'My name is $name';
  $test2 = "My name is $name";

Try printing the variables above in your own script and see the difference. $test1 will say ‘My name is $name‘ whilst $test2 will say ‘My name is Michael‘.

PHP provides several functions to test variables with, here is a table of the results from a couple of them:

$var is Function PHP returns
(not set) isset false
” (empty string) isset true
123 isset true
null isset false
” (empty string) empty true
123 empty false
(not set) empty true

Above, we use empty to test if a variable has a value, this function will return FALSE if variable has a non-empty and non-zero value. The following are values that PHP treats as false (zero):

  • "" i.e. empty string
  • 0 as an Integer
  • "0" as a String
  • NULL
  • FALSE
  • array()

Also note that empty only tests variables, anything else will result in a parse error. In other words, the following will not work: empty(trim($name)); (From www.php.net/empty).

Once a variable is defined (or set), you can use unset($var) or $var = null to destroy it.

Because PHP is weakly-typed, since PHP 5 (I think, maybe sooner), an additional operator has been included. By extending the standard boolean test operator ‘==’ to 3 equal signs, ‘===’, the variables being tested will also be tested to see if their base types match. In other words:

  (0 == '')

returns true because both are seen as false (0) by PHP, but

  (0 === '')

returns false because 0 is an integer and ” is a string, so their values match, but not their types.

This additional checking can also be used in the negative form, i.e. ‘!==’.

Using everything we’ve discussed above, a sensible way to read from the HTTP POST parameter super-global and set a default value is to use the ternary operator in PHP:

  $name = (isset($_POST['name'])) ? $_POST['name'] : 'none';

A good way to quickly play around with all these different functions, and to test your logic, is to use the PHP interactive shell (PHP 5.1 onwards):

$ php -a

Alternatively use PHP-Shell which has more features than the built-in shell (link below).

Related links

  1. PHP-Shell by Jan Kneschke
  2. http://www.php.net/manual/en/function.isset.php
  3. http://www.php.net/manual/en/function.empty.php
  4. http://www.php.net/manual/en/function.unset.php
Share this post
  • Digg
  • StumbleUpon
  • Reddit
  • del.icio.us
  • Facebook
  • muti
  • Mixx
  • Google
  • laaik.it

This entry was posted on Tuesday, January 23rd, 2007 at 7:53 pm and is filed under Code, MySQL. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

22 Responses to “B2B: Testing and defining variables in PHP”

  1. Chris M said this on

    Great tutorial bud :)

  2. Best Bath Store said this on

    This is often a wonderful web site which aids me to acquire far more data to the topic. I’ll bookmark it!

  3. KITESURF PAS CHER said this on

    Hi I love this discussion board I’m also passionated in extreme sport and methods to be far more successful…I discovered a piece technology that make me much more efficient I also like mode and fashion. Thanks again for your forum Bye KITESURF PAS CHER

  4. Lakenya Laverette said this on

    your post in fact aids, today i get the identical issues, and i’ve no concept on tips on how to solve the problem. thankgod i appear yahoo and discovered your post, it helps me get rid of my trouble. thanks as soon as againjust one factor, might i paste your article on my weblog? i will add the source and credit to your website.regards!

  5. Rodolfo Whitford said this on

    “,, I am really thankful to this topic because it really gives great information ~,;

  6. frenky said this on
  7. Ashleigh Moten said this on

    Right, what a good start however i’ll have to explore that a little bit more. Will show you exactly what more there is.

  8. Duncan Sawyers said this on

    This site won’t display correctly on my blackberry - you may wanna try and fix that

  9. Rhrfubfg said this on
  10. Tfxajiau said this on
  11. ugg bella moccasin said this on

    Hello! I simply want to give a huge thumbs up for the great information you’ve gotten right here on this post. I will probably be coming back to your weblog for extra soon.

  12. Nwiqkqic said this on

    Can you put it on the scales, please? lolita sex with animals kmlve

  13. Lbepedvx said this on

    Free medical insurance 12 years lolita models 0408

  14. Wannwsjm said this on

    Will I get travelling expenses? nude lolita pics free 1810

  15. Eybermxi said this on
  16. Shplagmz said this on
  17. Opjcrvfa said this on
  18. free online poker said this on

    Heya i am for the first time here. I found this board and I find It really useful & it helped me out a lot. I hope to give something back and help others like you aided me. Best wishes, free online poker

  19. Wbjbmswu said this on

    I’d like to speak to someone about a mortgage Preteen Lolita Pussy
    wdsem

  20. Cypehycle said this on

    SEVPRNTVKG ugg soldes LDTTAUNZWR http://www.ne-ns.com

  21. Ediwozam said this on

    I like watching football Dark Lolita
    6121

  22. Dennis Hosie said this on

    What about beautiful downtown oakland? buy Tera gold

Leave a Reply