Cool tips for PHP Programmers

1) My aversion towards addslashes:

My first-ever associate friend liked addslashes a lot. She liked it so much that she used it extensively even in places where it is not needed. She taught me its mantra too. I too held on to it fast like a catholic girl holding on to her rosary. Well, till the day I tried writing a mssql query.

For those, newbie PHP programmers, let me say what addslashes() does.

addslashes()Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte).

Well, I didn’t say that. But the PHP manual says it. From its very definition, a seasoned programmer can say how misleading and wrong it is. This should instead be written as “that can be quoted in mysql queries” and not database queries. Can anyone use addslashes in a MSSQL query? No, mssql has a different escape mechanism 😉

Ok, what should we do instead? Use mysql_real_escape_string() if you are using mysql** as your database. Escape quote by another quote in the case of mssql. A simple str_replace will do the trick here. Also, when you do it, take care to separate the database specific functions from the main code. That would save you from a lotta trouble later.

2) Beware of extract

I guess most of you would be familiar with extract function. It helps a lot when we use array functions.

int extract ( array var_array [, int extract_type [, string prefix]] )

This function is used to import variables from an array into the current symbol table. It takes an associative array var_array and treats keys as variable names and values as variable values. For each key/value pair it will create a variable

in the current symbol table, subject to extract_type and prefix parameters.

<?php/* Suppose that $var_array is an array returned from
wddx_deserialize */

$size = “large”;
$var_array = array(“color” => “blue”,
“size” => “medium”,
“shape” => “sphere”);
extract($var_array, EXTR_PREFIX_SAME, “wddx”);

echo “$color, $size, $shape, $wddx_size\n”;


The above example will output:

blue, large, sphere, medium

However, I would say that one shouldn’t use extract with USER INPUT arrays like POST or GET. For example, take the below code


// code follows

// access priviledged information


Just see, how easy it is to hack the above piece of code. All one needs to access classified information is to modify the url a bit and pass a administrator=1 string.

Note** – Please do not use mysql_real_escape_string with mssql functions. It would not work. This function is specific for mysql database.


Here I go

Its been a long time since I thought that I should do this. But I haven’t been able to put it in practise thanks to the 3 other blogs that I write. So, you would ask me what is new in here.

I am planning to share the technical tips that I have gained in my career. I hope you would find it useful. 🙂