For example, say I post some data to a php file, but I don't know what the names of those values are. Where I would normally perform $_POST["username"] or something similar. How would I go about getting a list of all the key/value pairs within $_POST
array_keys($_POST) will give you the array keys.
You can also do this to get values with key names:
foreach ($_POST as $key => $value)
{
//do stuff;
}
However!!! Why wouldn't you know what keys are in the post? You don't want hackers putting random stuff into a post, sending it to you, and processing away. There is nothing preventing them from putting in 1000s of entries.
Use array_keys to obtain all keys in $_POST super global array:
array_keys($_POST)
Simple example:
foreach (array_keys($_POST) as $key)
{
print $_POST[$key];
}
Related
Situation: An attempt to prevent DOM-based XSS.
My solution: Check if ANY GET fields are populated, since most DOM-based XSS appends to the end of URLs such as https://example.com/page?<script>XSS</script>
Question: Is there any way I can check if there is anything filled after "?", which usually holds the $_GET fields.
Additional information: I tried $_GET['']."%" to try to fish out anything that is there, did not work.
This is what appears to me using http://domain.tld/page?<script>XSS</script>.
$_GET is not empty as you say.
Just iterate every single $_GET attribute and make sure they are sanitized prior any data processing with your business model.
foreach ($_GET as $key => $attribute)
{
// do something with $key or $attribute!
}
There are several way possible .. eg:
You could iterate over $_GET
foreach( $_GET as $key => $value) {
// if any you can perform your check
}
or you can check for
if (isset($_GET) {
count($_GET) ; // the you know the number of elemns
}
You can use $_GET. Just print_r($_GET); If you have anything in query string after ? then data will be in $_GET array. If the $_GET array is blank then there is no data in query string
echo "<pre>";
print_r($_GET);
echo "</pre>";
Go to http://php.net/manual/en/reserved.variables.get.php
I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.
For example if i have
$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];
I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:
$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';
NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.
Is this possible?
You don't need a loop, you want extract:
extract($_POST); // But use caution, see below
Cautions and best practices
As noted in the comments this forces all parameters in the $_POST array into the current symbol space.
In global space
<?php
extract($_GET);
var_dump($_SERVER); // Can be overwritten by the GET param
?>
The code above illustrates the problem as shown in this answer — some pretty dangerous things can be overwritten in the global space.
Inside a function
function myFunc() {
// (Mostly) empty symbol space! (excluding super globals)
extract($_POST);
}
Inside a function, as the first line, no harm done.
Important note: You might think since $_SERVER is a super global, that this exploit could happen inside a function as well. However, in my testing, on PHP Version 5.3.4, it is safe inside a function — neither $_SERVER, $_POST, $_GET, $_SESSION, or presumably other superglobals, could be overwritten.
With options
You can also use extract with extract_type options that do not overwrite.
The best option to use, in my opinion, is simply to prefix all variables from extract:
// $_GET = test=1&name=Joe
extract($_GET, EXTR_PREFIX_ALL, "request_get");
echo $request_get_test; // 1
echo $request_get_name; // Joe
That way you don't have the overwrite problem, but you also know you got everything from the array.
Alternate - looping w/ conditional
If you wanted to do this manually (but still dynamically), or wanted to conditionally extract only a few of the variables, you can use variable variables:
foreach ($_POST as $key => $value) {
if (isset($$key)) continue;
$$key = $value;
}
(The example condition I've used is an overwrite prevention.)
Try not to use extract() when using $_POST. You may overwrite variables you want which will result in unpredictable behaviour. It is a bad habit to get into and while is dynamic may not be the best solution.
You can do something like this:
foreach($_POST as $key => $value)
{
switch($key)
{
case "name":
$name = $value;
break;
case "last":
$last = $value;
break;
}
}
You can actually use the built-in function called extract
Why not use a foreach?
foreach($_POST as $key=>$val){
${$key} = $val;
}
I just want to mention that you can improve foreach technique because we have in HTML the ability to name one of our form fields using square bracket notation, and if we do that, what HTML will do is it will submit a series of values as an array.
<input name="user[name]">
<input name="user[last]">
<input name="user[age]">
<input name="user[sex]">
Than use just one line of code to assign all values from input fields into local array $args.
$args = $_POST['user'];
So what that means is when we go to process the form, we're looking at an array of values instead of a bunch of single values that we have to go retrieve.
So we can just simply go to the post super global and ask for one item: that is user. And what we get back is an associative array. So instead of having to build up that array by going and retrieving all those values one at a time, we're instantly given an array, just because we named our form fields differently.
When I send over post data I do a print_r($_POST); and I get something like this...
Array ( [gp1] => 9 )
Is there a way to get the "gp1", the name sent over as a value? I tried doing.
echo key($_POST["gp1"]);
But no luck there, I figured it would echo gp1. Is there a way to do this?
you need
print_r(array_keys($_POST));
check this for more details http://php.net/manual/en/function.array-keys.php
You could use foreach to see each key-value pair, or use array_keys to get a list of all keys.
foreach ($_POST as $key => $value) {
// Do whatever
}
Well, if you can write $_POST["gp1"] you already have the key anyway ;)
key() works differently, it takes an array as argument:
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
So if you have not done anything with the array (no traversing), key($_POST) would give you the key of the first element of the array.
Maybe you want a foreach loop?
foreach($_POST as $key => $value) {
}
There are other methods to retrieve keys as to well. It depends on what you want to do.
Hello i got a question, i have a session array called 'addToCart', in there are multiple arrays with various id's, i would like to loop through these arrays with a foreach regardless of what the id name is. Does anyone know how i would approach this?
Does the following construction satisfy your needs?
foreach ($addToChart as $key=>$value){
// do anything you want with $key and $value
}
If you need to check "sub-arrays", you can check $value with is_array() function and add one more foreach loop inside.
I'm new to OOP and want to revamp this function to get rid of using globals.
function CatchListing() {
$parseform = array('itemnum','msrp','edprice','itemtype','box','box2','box25','box3','box4','box5','box6','box7','itemcolor','link');
foreach ($parseform as $globalName) {
$GLOBALS[$globalName] = mysql_real_escape_string($_POST[$globalName]);
}
}
I was told to use array_map & then extact, but I am not sure of how to structure this.
function CatchListing() {
$_POST['listing'] = array_map('mysql_real_escape_string', $_POST);
$nst = extract($_POST['listing']);
}
(listing is the form name btw)
Thanks
Be VERY careful about using extract with externally inputted values as from $_GET and $_POST.
you're much better off extracting the values manually to known values.
It's far too easy for an extract from _GET or _POST to clobber existing variables.
There are so many things to say and Jonathan makes a very good start. Every time the user has the opportunity to play with your internal data and you don't check them, there is a huge "opportunity" (depends on the view..) that something goes wrong. Here is another approach on how to "maybe" get where you want to go:
<?php
function Sanitize($string){
return mysql_real_escape_string(trim($string));
}
function CatchListing(){
foreach($_POST as $key => $value) {
$key = Sanitize($key);
$value = Sanitize($value);
if($key && $value && !$GLOBALS[$key]){ /* prevent overwriting existing globals*/
$GLOBALS[$key] = $value;
}
}
}
global $nice;
$nice = "working";
CatchListing();
print_r($GLOBALS);
?>
To be honest, it still has not really anything to do with OOP and furthermore should be seen as a procedural approach. Personally I would use an additional and reusable function to "sanitize" the input, because you never know, if someday you want to change your database or the "escape" function and then you exactly know where to look for possible changes. Ah one more thing: Are you certain that you don't know all the possible names of all the variables you have to expect? Maybe you can predetermine them and put them in another array and check each user supplied argument with in_array.
To completely get rid of the usage of globals in your code, and also to make it much better overall, you can do something along these lines:
stop using $_POST, as it's a superglobal. When code needs values from superglobals, pass them as parameters
don't store values into $GLOBALS. If you need to return more than one value, consider returning an object or an array
Here's how I think I would modify your code to improve it:
function CatchListings($listings) {
$filteredListings = array_map('mysql_real_escape_string', $listings);
//I assume you only need the values in the array in the original snippet,
//so we need to grab them from the parameter array and return only that
$requiredListings = array();
$requiredKeys = array('itemnum','msrp','edprice','itemtype','box','box2','box25','box3','box4','box5','box6','box7','itemcolor','link');
foreach($requiredKeys as $key) {
$requiredListings[$key] = $filteredListings[$key];
}
return $requiredListings;
}
To use this function, you simply do $result = CatchListings($_POST);. Same result, no globals used.
There is one thing to consider, though. It may not be best possible form to just pass a randomly filled array (ie. $_POST) to the function, and expect it to contain specific keys (ie. $requiredKeys array). You might want to either add logic to check for missing keys, or process the post array before passing it.