confusion receiving an string value with functions list() and split() - php

buy.php
<form action="cart.php">
<input style="width:10px; margin-left:9px; " name="price[]" type="checkbox" value="' . $variety['price']. '_'. $variety['variety'] '_'. $product['name']. '" />
</form>
I am sending the input form above to cart.php inthere I receive it like:
list($aDoor, $variety,$productname) = split('_', $_POST['price']);
$aDoor = array();
$variety = array();
$productname= // $productname is a string how can I set it up here?
foreach ($_POST['price'] as $p)
{
list($a, $b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname =$c; // and I have put it equal to the variable $c here
}
The only problem above is receiving the index $product['name'] coming from the form in buy.php
In cart.php I have set it up to be received by $productname but as you can see this is an string not a array how can I set it up when it is an string in with the functions list() and split() it confuses me.

Ok. There's a few things wrong with your script.
1) You've not specified a method on your form tag, so by default the data will be submitted as a 'GET'. You're using $_POST in your script, so those values will be blank and the foreach loop will fail as $_POST['price'] doesn't exist.
2) You're naming the checkbox as "price[]". The [] tells PHP that there will be multiple values submitted with this same name, so that $_GET['price'] will be an array. Your first few lines of code will then fail, as split works on strings, not arrays. You'll end up with the following values assigned
$aDoor = "Array"
$variety = NULL;
$productname = NULL;
PHP attempts to convert your $GET['price'] array to a string, but this defaults to just coming back as the string 'Array', and there's no "" values in there, so the rest of the list() variables having nothing to be assigned to them, so they become null.
3) Split's been deprecated and will be removed in PHP 6, so use explode() instead (as you do just a few lines later)
4) You then immediately trash those values by assigning empty arrays for $aDoor and $variety, so in effect the split line was useless
The foreach loop looks fine, though you'll want to assign to a $productname array, instead of a string, so use $productname[] = $c;
5) I would, however, not store the data you're explode()ing in three seperate arrays. It would make more sense to
store it like this:
$products = array();
foreach($_POST['price'] as $p) {
list($a, $b, $c) = explode('_', $p);
$products[] = array('aDoor' => $a, 'variety' => $b, 'productname' => $c);
}
This way you don't have to pass around 3 arrays (or make them 'global') in any functions that use this data, you can pass just a single variable (ie: updateInventory($products[7]); )
5) If this shopping cart script was released into the wild, it could be a gaping security hole on the server. What would stop someone from constructing their own price by passing in something like "$0.00_fire engine red-ferrari" as the price field? I've always wanted a free Ferrari, and round-tripping pricing data through the user's browser is a nice way to get it. Never, ever, trust a client to NOT hack up critical data, such as its price.

$productname = '';

If you don't specify the method attribute of the form, the default is GET. In your script you are using POST, try putting POST method to your form:
<form action="cart.php" method="post">
Secondly, even if $productname is a string but you can convert it to array (like you have done for other vars) by suffixing it with [], so your code becomes:
$aDoor = array();
$variety = array();
$productname = array();
foreach ($_POST['price'] as $p)
{
list($a,$b,$c) = explode('_', $p);
$aDoor[] = $a;
$variety[] = $b;
$productname[] = $c;
}
Now these three arrays contains your data.

Related

Fatal error: Can't use function return value in write context error in PHP

I need to get values of html element name 'item_name1','item_name2','item_name3'...so on using loop. But it is showing this fatal error. Please help to resolve...
Code is:
$item_name = array();
$item_qty = array();
$item_value = array();
for($i=1;$i<=php_count;$i++){
$item_name($i) = $_POST['item_name+$i'];
$item_qty($i) = $_POST['item_qty+$i'];
$item_value($i) = $_POST['item_value+$i'];
echo($item_name($i));
}
You need square brackets [ ] instead of parentheses ( ) when accessing your arrays. The former are used for array indexing while the latter are used for function calls.
Since you are essentially calling your array like a function and you have the result of that call on the left-hand side of an assignment, you are getting the error that you can't write to a function return value.
And by the way: Currently you are literally accessing the indexes item_name+$i and such of $_POST because you have the +$i part inside of the string. Use $_POST['item_name' + $i] instead.
as requested
use square brackets for array elements
use double quotes to allow variable processing within string context
use variable for php count
$item_name = array();
$item_qty = array();
$item_value = array();
for($i=1;$i<=$items_count;$i++){
$item_name[$i]= $_POST[“item_name+$i”];
$item_qty[$i] = $_POST[“item_qty+$i”];
$item_value[$i] = $_POST[“item_value+$i”];
echo($item_name[$i]);
}
———
alternative solution
simplify by changing your form input names to allow arrays of data
Input names such as item[0][name] would allow you to simply loop through an item array!
foreach($_POST['item'] as $item) {
$item_name = $item['name'];
...
Your code have to like this
$item_name[$i] = $_POST['item_name'.$i];
$item_qty[$i] = $_POST['item_qty'.$i];
$item_value[$i] = $_POST['item_value'.$i];
echo($item_name[$i]);

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.
}
?>

all variables from url

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.

Using form inputs in PHP to populate nested objects

I am trying to process the submitted results for a form, containing data for a number of employees. The form inputs have names like "employees[1]_firstName" which needs to map to the PHP variable $companydata->employees[1]->firstName
When populating the $_POST array, PHP sees square brackets, and tries to make a multi-dimensional array, but gets it wrong (ignoring everything after the opening bracket)
This replicates $_POST but without the corrupted array keys: Note that I've taken out a foreach loop to simplify the question.
$post_data = explode('&', file_get_contents("php://input"));
// Result: $post_data = array('employees%5B1%5D_firstName=Timothy'
list($key, $value) = explode('=', $post_data[0]);
$key = urldecode($key);
$value = urldecode($value);
// Result: $key = 'employees[1]_firstName', $value = 'Timothy'
However things go wrong when I try to use variable variables:
$post_key_parts = explode('_', $key);
// Result: $post_key_parts = array([0] => 'employees[1]', [1] => 'firstName')
$Companydata->$post_key_parts[0]->$post_key_parts[1] = $value;
// Expected result: Element [0] in array $employees => 'Timothy'
The actual result is a variable with square brackets in its name '$employees[0]',
and no change to the $employees array. Putting curly brackets round the {$post_key_parts[0]} doesn't help.
I am trying to find a flexible solution that will also work for names of different lengths eg: employees[0]_address_lines[2] or employees[0]_addresses[1]_postcode
I'm happy to avoid the sin of variable variables, but I can't think of an elegant way to do it with regexes or something like that.
I would suggest you change the inputs' names. To make use of the built-in features of PHP. [] creates an array for you, use arrays then, as you are intended to use them.
I had the same problem and came up with this:
//HTML part
<input name="employee_firstName[]">
<input name="employee_address[]">
//PHP part
<?php
$info = array("firstName", "address")
foreach ($info as $i) {
foreach ($_POST["employee_".$i] as $k => $v) {
$companydata->employees[$k]->$i = $v;
}
}
?>
NOTE I don't think you can do this for things like employees[0]_address_lines[2]. Or maybe try employees[0][address_line][] and use it as an array, but I'm not sure that works.

ow to handle possible duplicate array keys

I am trying to figure out how I can handle possible duplicate array keys.
I have this form with a select dropdown which can select multiple options (more than 1). And I am using jQuery.serialize() to serialize the form on submit.
The serialized string for a multi-select element would look like so:
select=1&select=2&select=3 // assumming I selected first 3 options.
Now in the PHP side, I have the following code to handle the "saving" part into a database.
$form_data = $_POST['form_items'];
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
$arr[$key] = $value;
}
Ok this all works for the rest of the form elements but when it comes to the select element, it only picks the last selected key/value pair. So my array now looks like this:
Array ( [select_element] => 3)
What I need, is for it to look like:
Array ( [select_element] => '1,2,3')
So I guess what I am asking is based on my code, how can I check if a key already exists and if it does, append to the $value.
If you can modify the client-side code, I would rather change the name of the select to select[], that way it will be parsed as an array in your server script.
You can't have multiple keys with the same name... They're unique keys. What it's doing is setting select = 1, then select = 2, then select = 3 and you end up with your final value of 3.
If you want to allow multiple choices in your select menu, you should change the name of the element so that it submits that data as an array, rather than multiple strings:
<select name="select[]" multiple="multiple">
which should result in something like this instead:
select[]=1&select[]=2&select[]=3
and when PHP requests that data, it will already be an array:
$data = $_POST['select'];
echo print_r($data); // Array(1, 2, 3)
PHP has its own way of encoding arrays into application/x-www-form-urlencoded strings.
PHP's deserialization of x-www-form-urlencoded is implemented by parse_str(). You can think of PHP as running these lines at the beginning of every request to populate $_GET and $_POST:
parse_str($_SERVER['QUERY_STRING'], $_GET);
parse_str(file_get_contents('php://input'), $_POST);
parse_str() creates arrays from the query string using a square-bracket syntax similar to its array syntax:
select[]=1&select[]=2&select[]=3&select[key]=value
This will be deserialized to:
array('1', '2', '3', 'key'=>'value');
Absent those square brackets, PHP will use the last value for a given key. See this question in the PHP and HTML FAQ.
If you can't control the POSTed interface (e.g., you're not able to add square-brackets to the form), you can parse the POST input yourself from php://input and either rewrite or ignore the $_POST variable.
(Note, however, that there is no workaround for multipart/form-data input, because php://input is not available in those cases. The select=1 and select=2 will be completely and irretrievably lost.)
Ok, I was able to resolve this issue by using the following code:
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
So now the loop looks like this:
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (array_key_exists($key, $arr)) {
$arr[$key] = $arr[$key].','.$value;
} else {
$arr[$key] = $value;
}
}
This will essentially string up the value together separated by a comma which can then be exploded out into an array later.
You should change your client-side code to send the augmented value: array.join(","); and use that in your PHP side. Because when your data reaches your script, the other values have already been lost.
This should give you the solution you require
$form_data = str_replace('&','####',$form_data);
$form_data = urldecode($form_data);
$arr = array();
foreach (explode('####', $form_data) as $part) {
list($key, $value) = explode('=', $part, 2);
if (isset($arr[ $key ])) {
$arr[$key] = ','.$value;
} else {
$arr[$key] = $value;
}
}

Categories