all variables from url - php

I have a code like that:
session_start();
$user = $_GET['user'];
$mode = $_GET['mode'];
$id1 = $_GET['id1'];
$id2 = $_GET['id2'];
$id3 = $_GET['id3'];
$id4 = $_GET['id4'];
$id5 = $_GET['id5'];
$id6 = $_GET['id6'];
$id7 = $_GET['id7'];
$id8 = $_GET['id8'];
$dep= $mode;
switch ($dep)
{
case "3m":
$dep = "Text 1";
break;
case "all":
$dep = "More text";
break;
default:
$dep = "Text1";
}
There are more other cases. I think I will have more id's and cases soon. Is there a simpler way to get all id's from URL push them into PHP code for evaluating?
I have found a code foreach:
foreach($_GET as $key => $value) {
echo 'key is: <b>' . $key . '</b>, value is: <b>' .$value. '</b><br />';
}
And it gets all variables from URL, but how to change the code in order to have it like this:
$variable = $_GET['variable'];
Any help appreciated :)

Use arrays, that's exactly what they're for. Name the parameters in the URL like:
id[]=1&id[]=2&...
Then $_GET['id'] is an array which you can easily loop through.
Many ids means you're looking for an array of ids, not id1, id2, id3 etc. An array allows you to access them virtually the same way as $id[1], $id[2] etc, but without the headache of needing to herd hundreds of independent variables.
There's also no need to assign each value from $_GET into its own variable, you can use those values directly from $_GET. They're not getting any better by assigning them into individual variables.

Assuming I understood correctly and you want all GET variables to be actual variables you can use, there's a function extract to do that.
However, as noted in the documentation:
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 flags 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.
So basically you should not do this unless you have good reasons, and be careful if you do as to not overwrite any existing values.
However, if your alternative is to do this:
foreach($_GET as $key => $value) {
$$key=$value;
}
then extract is certainly better, as a) you can set it to not overwrite any existing variables, and b) you can have a prefix, so those imported variables can be distinguished. Like this:
extract ( $_GET, EXTR_SKIP);
For $user, $mode, $id which don't overwrite anything, or
extract ( $_GET, EXTR_PREFIX_ALL, 'user_input' );
for $user_input_mode, $user_input_user, $user_input_id etc.

function getIDs()
{
$ids = array();
if(isset($_GET['id']))
{
foreach($_GET['id'] as $key => $value)
{
$ids[$key] = $value;
}
}
return $ids;
}
If you can get your URL to send an array of id GET parameters to a PHP script you can just parse the $_GET['id'] array in the above function, assuming the URI looks like ?id[]=1&id[]=2&id[]=3
$ids = getIDs();

You can write
foreach($_GET as $key => $value) {
$$key=$value;
}
this will assign every key name as a varibale.

Related

How to use variable inside the parameter of $_POST in php

I will be getting some certain amount of data. I will get the number for which the for loop to be run.
For example
I get the number 3 and I will get three parameters like par1,par2 and par3 then how should I pass this par1 in the $_post
like
$i=$_POST["number"];
for($i=1;$i<=$n;$i++)
{
$par.$i = $_POST["par".$i];
}
Here I cant get the value from $_POST["par".$i];
As it is not able to get the variable inside the paramater of $_POST
Any help will be thankful
I suggest that you create a new array $par and there you will put by index all the par you will have like this:
$i=$_POST["number"];
$par = [];
for($i=1;$i<=$n;$i++)
{
$par[$i] = $_POST["par".$i];
}
After that if you want to go throw all pars you can simply use foreach like this:
foreach($par as $key => $value) {
// $key will be 1,2,3
// $value will be the value from $_POST["par" . $i]
}
The . is to concatenate two strings in PHP, and you can't create a new variable like you tried. If you want to have in $par1, $par2 and $par3 you can do like this:
${"par" . $i} = $_POST["par".$i];
But I don't recommend this way because it's more hard to handle.
One Way
According to your question.
<?php
$n = $_POST["number"];
$par = "par";
for($i=1; $i<=$n; $i++){
$par.$i = $_POST["par".$i];
}?>
Alternative Way
In this scenario,
For example I get the number 3 and I will get three parameters like
par1,par2 and par3 then how should I pass this par1 in the $_post.
Better, make 'par' input name as an array type as 'par[]' (<input type='text' name='par[]'>) in your file instead using par1, par2 .. par(n).
And, no need to worry in submit page.
<?php
$n = $_POST["number"];
for($i=1;$i<= $n;$i++){
$newPar = $_POST["par"][$i];
// Write here your logic to use how you want.
}
?>

Get names of GET method variables

I have about 5 variables in GET method. They almost always have different names, encoded mostly. How i can get name (not value) of those variables.
example:
$_GET['orchid'] = red;
$_GET['xyc'] = wrack;
and after that, next time i open the page:
$_GET['rose'] = red;
$_GET['gzuy'] = bottle;
Values are not important for now, in this case I need names of variables: "orchid", "xyc" or in second case "rose" and "gzuy".
array_keys($_GET)
For more informations, see the link bellow:
http://php.net/manual/function.array-keys.php
foreach ($_GET as $key=>$value){
echo $key;
}
array_keys() should do the trick:
$keys = array_keys($_GET);
foreach ($_GET as $key => $value) {
//Line below is optional to get around empty values.
if (!empty($value))
echo $key, ' ';
}
The above code will print out all of the set $_GET variables, having file.php?moo will mark moo as set but with a value of nothing. The below snippet will simply return an array just containing the names of the $_GET variables which can then be used in $_GET[$keys[0]] for example to recall its value.
array_keys($_GET);
Docs:
foreach loop
array_keys()

Pushing values from a $_Get query to a value using implode

I am attempting to use a for loop or for each loop to push the values from a get query to another variable. May I have some help with this approach?
Ok here is where I am:
for ($i = 0 ; i < $_GET['delete']; i++) {
$_jid [] = $_GET['delete'];
}
You don't actually need a loop here. If $_jid already is an array containing some values, consider just merging it with $_GET['delete'].
if (is_array($_jid)) {
$_jid = array_merge($_jid, $_GET['delete']);
}
If $_jid is not an array and doesn't exist except as a container for $_GET['delete'] you do can just assign the array. There is no need to loop at all.
$_jid = $_GET['delete'];
Of course in that case, you don't even need to copy it. You can just use $_GET['delete'] directly, in any context you planned to read from $_jid.
Update:
If the contents of $_GET['delete'] are originally 923,936, that is not an array to begin with, but rather a string. If you want an array out of it, you need to explode() it on assignment:
$_jid = explode(',', $_GET['delete']);
But if you intend to implode() it in the end anyway, there's obviously no need to do that. You already have exactly the comma-delimited string you want.
As you can see if you do a var_dump($_GET), the variable $_GET is a hashmap.
You can easily use a foreach loop to look through every member of it :
foreach($_GET as $get) // $get will successively take the values of $_GET
{
echo $get."<br />\n"; // We print these values
}
The code above will print the value of the $_GET members (you can try it with a blank page and dull $_GET values, as "http://yoursite.usa/?get1=stuff&get2=morestuff")
Instead of a echo, you can put the $_GET values into an array (or other variables) :
$array = array(); // Creating an empty array
$i = 0; // Counter
foreach($_GET as $get)
{
$array[$i] = $get; // Each $_GET value is store in a $array slot
$i++;
}
In PHP, foreach is quite useful and very easy to use.
However, you can't use a for for $_GET because it's a hashmap, not an array (in fact, you can, but it's much more complicated).
Hope I helped

using a foreach loop to initialize variables

I have built an empty associative array whos keynames refer to submitted post data. I can capture the postdata just fine, but I run into trouble trying to instantiate variables who's names match the array key.
for example:
$insArray = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
foreach($insArray as $key=>$value){
if (filter_input(INPUT_POST, $key) != ''){
$key = stripslashes(filter_input(INPUT_POST, $key));
$insArray[$key] = $key;
}
}
First line creates the empty array, then the foreach loops through this array. Now it gets tricky.
filter_input(INPUT_POST, $key) captures the value located in the post data matching the current key, rUsername in this case
$key is where the problem lies. I want the NAME of the new variable to be the associative key name, for example I want to replace $key with $rUsername in the first iteration, $rPass in the second, and so on. I tried using two $$, but I know that's not right. Never tried doing this before, but it would be helpful if I could figure it out.
UPDATE:
This is the final code which was a combination of two of the answers provided.
if (isset($_POST['submit'])) {
//Build array of variables to be put into database
$insArray = array('rUsername'=>'', 'rPassword'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCheckOption'=>'', 'rEmail'=>'');
foreach(array_keys($insArray) as $key){
$insArray[$key] = filter_input(INPUT_POST, $key);
$$key = filter_input(INPUT_POST, $key);
}
}
Gave me exactly the output I wanted, thanks guys!
You're not accessing $_POST at all, so all you're doing is taking some array members you defined yourself, filtering them for harmful POST characters (why would you attempt to inject your own code?) and then creating a new array from those self-defined key values.
If I'm guessing right at what you want, it should be this:
foreach(array_keys($insArray) as $key) {
$insArray[$key] = stripslashes(filter_input(INPUT_POST, $_POST[$key]));
}
The use of stripslashes suggests that you're on a braindead version of PHP which has magic_quotes enable. You should upgrade to a modern version of PHP and/or turn them off.
The solution is change
$key = stripslashes(filter_input(INPUT_POST, $key));
to
$$key = stripslashes(filter_input(INPUT_POST, $key));
See http://www.php.net/manual/en/language.variables.variable.php
Also, recheck your code, which are doing some mistakes..
If I understand you correctly, Im going to suggest this approach:
$defaultValues = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
$values = array_map('stripslashes', array_merge($defaultValues, array_filter($_POST)));
extract($values, EXTR_SKIP);
echo $rUsername;
echo $rPass;
.........
By using the snippet above, you have to take into account the following
Im using the extract function with EXTR_SKIP so you dont overwrite existing variables. Make sure to only use the variables you need in your code and sanitize them appropietly.
By using array_filter on the $_POST superglobal im "erasing" all empty or null variables. so if an expected key was not sent via $_POST, it defaults to the value specified by the $defaultValues array.
I dont quite understand why you are using filter_input without the third parameter (filter constants).
Hope this will help, If not may be I have misunderstood the problem.
Instead of
$key = stripslashes(filter_input(INPUT_POST, $key));
$insArray[$key] = $key;
Try
$insArray[$key] =stripslashes(filter_input(INPUT_POST, $key));
Then after the foreach loop
extract($insArray);

PHP - Save value AND name using $_POST

I'm currently using the following format to save a value from an HTML form $item_name=$_POST['item_name'];
This saves the value, but how to I also save the name attribute in a variable?
Thanks in advance!
Assuming you want to store each element of $_POST variable as a key-value pair, then you can try:
$var = array();
foreach($_POST as $key => $val) {
$var[$key] = $val;
}
I'm saving a lot of values and want to avoid typing each one out.
Please, make your mind first.
Global variables are intended to be typed by hand.
If you want some automated processing - just keep them in a form of array.
Looks like rdt.exe's answer is what you're looking for.
maye you noticed you have to use the name to access the $_POST-array and get the value. if you want to store the name in a variable, too, just do:
$item_name_name = 'item_name';
$item_name_value = $_POST[$item_name_name];
you could also use some kind of loop to dynamically create variables with the according names like this:
foreach( $_POST as $name => $value ){
$$name = $value;
}
both ways are some kind of unnecessary and useless in my opinion, but you havn't stated what exactly you're trying to achive - so maybe this helps.
An alternative approach:
$keysarray = array_keys ( $_POST);
print_r( $keysarray);
This will give you all the keys in array
The function you are looking for is called extract.
This will create variables for all the $key=>$val pairs in the array.
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound');
export($_EXAMPLE);
echo $bird; # prints "chicken"
echo $dog; # prints "greyhound"
Watch out though - this is a huge security risk. So are the solutions described in some of the other answers.
The problem with doing something like this is that a user can tamper with the POST data, and set parameters other than the ones she is supposed to set. If they set variables that are actually variable names in your application, those variables can be overwritten.
$is_admin = false;
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound', 'is_admin' => 'true');
export($_EXAMPLE);
if ($is_admin) { # this will now evaluate to true.
# do sensitive stuff...
}

Categories