What is the best way for retrieving POST and GET variables in your opinion? the classic way (e.g. : if (isset($_POST["var"])) { $var = addslashes(htmlentities($_POST["var"])); } else { $var = ""; }) is too long for the big scripts, isn't? thanks
Well, you can wrap it on a function and it will be short. My personal opinion about your code : htmlentities is not necessary on input-reading. You should put it when you will echo the var / somehow display it on the client. So a string like this <b>Yay !</b> HTML: Will be still like that on the database (except you add some mysql_real_escape_string when inputting it) But it will be converted to the html-escaped version when you want to echo it $s = '<b>Yay !</b>'; echo htmlentities($s); PHP: Usually, addslashes (or actually i prefer mysql_real_escape_string) is used when i am about to use it on a database query. <?php function read_post($n) { $n=trim($n); $s=''; if (isset($_POST[$n])) { $s=trim($_POST[$n]); } return($s); } $name = read_post('name'); $age = read_post('age'); $address = read_post('address'); ?> PHP:
I prefer to build an array of the POST or GET arrays instead of setting individual variables. The array I build escapes the actual value posted if I need it in a database. Also use mysql_real_escape_string instead of addslashes. Do a google search for comparison of those 2 and you'll know why. Thanks
You can use the extract() function. It assigns all elements of the array into variables using the key. extract($_POST); // same as foreach ($_POST as $key => $value) { eval("{$key} = {$value};"); } PHP:
Hey, the PHP manual says; "Do not use extract() on untrusted data" GET and POST variables are really untrustable So i'll not use this nice function, but thanks anyways!
You can always sanitize any way you like.. foreach ($_POST as $key => $value) { eval("\$_POST[{$key}] = mysql_real_escape_string({$value});"); } PHP:
You're right, never use extract Here is a little bit code just in case eval is disabled (yes, sometimes on some hosting, eval is disabled) <pre> <?php /* URL is test.php?name=john&age=13&state=LV&phone=1092&id[]=111&id[]=222 */ $my_vars = array(); foreach ($_GET as $name=>$value) { // give some prefix here, to avoid overwriting your other variables $my_vars['my_prefix_here_'.$name] = $value; } parse_str(http_build_query($my_vars));// some magic powder unset($my_vars);// it's useless now, let's dump it var_dump($my_prefix_here_name);// magic happens var_dump($my_prefix_here_age);// magic happens var_dump($my_prefix_here_state);// magic happens ?> </pre> PHP: