In my previous post i ask how to create variables from an array ( PHP Variables made with foreach ) i got several answers and i was testing extract() but i have seen several against it for security reasons.
Now my question here is how can i use extract in a secure way from a $_POST that has an array that was made using jquery serialized.
With secure i mean that if a user inputs the wrong data, the secure way can take care of that with no problems.
THe PHP Site has a small warning in the extract command the says the following:
Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.). If you do, for example if you want to run old code that relies on register_globals temporarily, make sure you use one of the non-overwriting extract_type values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.
It warns about the use but does not provide an example at least of how to solve the user of extract in a secure way.
The extract() Function is an inbuilt function in PHP. The extract() function does array to variable conversion. That is it converts array keys into variable names and array values into variable value. In other words, we can say that the extract() function imports variables from an array to the symbol table.
The compact() function is an inbuilt function in PHP and it is used to create an array using variables. This function is opposite of extract() function. It creates an associative array whose keys are variable names and their corresponding values are array values.
In PHP, a variable is declared using a $ sign followed by the variable name.
Function extract extracts only those key=>value pairs where key is valid identifier not conflicting with existing variables. So probably keys in your $_POST are either not a valid identifiers or are conficting with existing variables.
The best option is to not use extract()
at all. It's a bad design decision from the days when PHP was the equivalent of wet toilet paper for writing secure code.
It may be painful, but it is far better to write out a long sequence of:
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
etc...
or simply use $_POST['var1']
and company everywhere in your code.
As soon as you start using extract, you're giving malicious users a potential way into your code, no matter how much time/effort you put into it. You don't drill a hole through a bank vault door because it's too annoying to have to open the door each time to let some money out. Once there's a hole, it will be exploited.
Don't use extract(), just use foreach() on POST/GET to create your own array/object. extract() will be nightmare to debug once your code starts getting bigger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With