I have the same question but...I'm redirecting the user depending on an if statement using headers to a dynamic page that is constructed through a function. For that function to work properly, it needs the parameters passed in the GET portion of the headers.
According to what to the answers provided, this is a bad practice. What way should I be doing it?
function page($title,$msg){
$title = $_GET['title'];
$msg = $_GET['msg'];
echo '<h1>'.$title.'</h1>';
echo '<p>';
switch($msg){
case 1:
echo 'dwasdwadawdwadwa';
break;
case 2:
echo 'wasdadwadwdad';
break;
default:
echo 'wadasdasd';
break;
}
echo '</p>';
}
ps: feel free to point out anything else you see wrong.
I found this but it doesn't really help me.
The answer to the question you linked suggests that functions should not rely on any external (e.g. global) variables.
$_GET
and$_POST
(amongst others) are 'super globals', a language feature of PHP that makes them available in any scope. This means they may be unexpectedly modified from anywhere in your scripts.One way to help avoid this is to avoid using super globals in methods and instead - as the answer to the other question suggests - is to instead require parameters for the variables you would otherwise get from the super globals.
E.g., instead of:
You would use:
In your situation, what you would want is:
Then, when you call
page
you would call it as:Although you aren't necessarily using the $_GET input for something that requires security considerations (in this case), it's a bad practice not to be sanitizing values from the URL.
Not only should you be checking for malicious input (especially if you are using the input to query a database), but you should be validating that expected integer values are indeed integers, and required strings are not empty.
Also, your
page($title, $msg)
function accepts$title
and$msg
and sets them, even though they are not passed by reference.If you expect to modify the input parameters, pass them by reference.
If you need to use the input parameters, don't overwrite them immediately.
If you don't need input parameters and only use values from
$_GET
locally to your function, declarepage()
without any arguments.Not sure if i understand your question, but here is some code i use handle my ajax calls with:
This means "operation" refers to your method name inside MyClass and i dont have to add a new switch statement for each method. Now i can just add a function "addRecord($args)" to MyClass, and my ajax call would look like this:
your php function receives the arguments in an array, so inside function
addRecord()
you have to access the variables like$args['name']
and$args['dob']
, and it dosnt matter how many parameters you have to pass on to your method.Make sure you use prepared statements here or proper escaping to prevent sql injections.
Why do you need to use GET? you can access all the same properties if you use POST which is also more safe