PHP: How to Make Life Easier with References

Posted by Jetlogs @ 8:30 am
Category: PHP,Web Development

Don’t you just hate it when you have to write very long codes such as below?

$name = mysql_real_escape_string(strip_tags($name));
$email = mysql_real_escape_string(strip_tags($email));
$address = mysql_real_escape_string(strip_tags($address));

Even if you created a function to make coding easier, it can still be a little bit tedious:

function escape_mysql($string)
{
	return mysql_real_escape_string(strip_tags($string));
}

$name = escape_mysql($name);
$email = escape_mysql($email);
$address = escape_mysql($address);

I’ll demonstrate a simple technique to make your life easier by using PHP’s references. By passing variables by reference, we can get rid of the variable assignment on the function’s return value. Here is how if should look like in the end:

function escape_mysql(&$string)
{
	$string = mysql_real_escape_string(strip_tags($string));
}

escape_mysql($name);
escape_mysql($email);
escape_mysql($address);

By passing variables by reference in our escape_mysql() function, the variable assignment no longer becomes necessary since the function will do it instead. Now that is a lot more easier to code and understand isn’t it?


3 Comments »

3 Comments to “PHP: How to Make Life Easier with References”

  1. Pingback:
    1
    Jetlogs.org » PHP: Humor and SQL Injections

    [...] really got to me with this comic. It really shows why you should always filter your inputs, especially when you’re going to use them in an SQL [...]

  2. prospect_shin
    2

    would this actually work if i were to write something similar for my database? such i can sanitize the input from a (user,password) and (post,title,e.t.c) ??

  3. Pingback:
    3
    Vivek Soni, Strong theoretical - yet practical - and technical background with a Master of Computer Science (with Business Option).

    [...] Jetlogs.org (0) Comments [...]

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License