...

View Full Version : Help with basic function to initialize page required variable



quadrant6
10-05-2006, 01:32 AM
The idea is that instead of repeating this sort of thing at the top of my scripts:



$id = $_REQUEST['id'];
if($id == '')
...


..I can simply have a function called int_var and do this




function int_var($var){

if(!isset($_REQUEST[$var]) && !isset($_SESSION[$var])){
echo "Error: This page requires the variable '<b>".$var."</b>' to be passed";
exit;
}

if($_REQUEST[$var] != ''){
$$var = $_REQUEST[$var];

} else if($_SESSION[$var] != ''){
$$variable = $_SESSION[$var];
}

}

// this page expects either $_REQUEST['id'] or $_SESSION['id']
int_var('id');



What I should end up with from this example above is

$id = '2';

But it just doesn't seem to be creating the $id variable.

Any suggestions?

firepages
10-05-2006, 02:30 AM
You are expecting $$var to be accessible outside the function scope which it will not be without declaring it global or passing it by reference.

in the scope of what I think you want ....



<?php
function required($vars){
foreach($vars as $v){
if(!empty($_REQUEST[$v])){
global $v; $v= $_REQUEST[$v];
}elseif(!empty($_SESSION[$v])){
global $v; $v= $_SESSION[$v];
}else{
die("Error: This page requires the variable '<b>".$v."</b>' to be passed");
}
}
}

required(array('id','blah'));
echo $id;
echo $blah;
?>


..should work...
Personally however I prefer not to do `$id=$_GET['id']` etc and prefer to work with the original $_GET['id'] etc , in which case something like the below would just check the variables exist.



<?php
function required($vars){
foreach($vars as $v){
if(empty($_REQUEST[$v]) && empty($_SESSION[$v])){
die("Error: This page requires the variable '<b>".$v."</b>' to be passed");
}
}
}
?>

You could also take this opportunity to filter the incoming variables for injection/script attacks & so on via addslashes(), htmlentities() etc..

quadrant6
10-05-2006, 03:31 AM
Thanks :)



Personally however I prefer not to do `$id=$_GET['id']` etc and prefer to work with the original $_GET['id'] etc


Is that because it's more obvious where those vars came from when your working with them?




You could also take this opportunity to filter the incoming variables for injection/script attacks & so on via addslashes(), htmlentities() etc..


I haven't done that before but probably should!, especially since I'm inserting data into MySQL

syosoft
10-05-2006, 09:17 AM
if your concern is data insertion into mysql, look into type setting and mysql_real_escape_string()



$query = 'INSERT INTO table (id,name) VALUES('.(int)$id.',"'.mysql_real_escape_string($name).'")';



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum