I've a very strange problem with a session variable.
This var is an associative array. I create this in a page (page A) with a lot of filterable items. I save filters in a session var
$_SESSION['filter'] = Array ( 'm' => 'acrylic', 'a' => 'P', 'c' => 1960 );
the user can go to a detail page (page B) but here I have
$_SESSION['filter'] = Array ( 'm' => 'acrylic', 'a' => 'P');
the strange is that when I go i the detail page I miss the last item in the associative array
so I can't go back with the right filter info.
I build the session var in this function, the options are passed in the URL example: http://www.web.com/artworks/a-P/c-1960/o-private+collection
the argument $args with this URL will be this array('a-P', 'c-1960', 'o-private+collection')
private function filter($args){
// options
$f = array('a','c','u','t','m','o');
$a = array();
foreach($args as $i){
$t = explode('-', $i);
if (in_array($t[0], $f)){
$a[$t[0]] = urldecode($t[1]);
$this->suffix .= '/'.$i;
}
else if(is_numeric($i))
$a['pp'] = intval($i);
}
$_SESSION['filter'] = $a;
return $a;
}
I call this in page A, In the page B I don't call this function the only interaction is
if (isset($_SESSION['filter'])){
print_r($_SESSION);
...
Someone can help me?
Thanks
You have to call session_start somewhere in your script before adding new values into $_SESSION, otherwise they will not persist. Do you do that?
I don't know exactly but try with giving last varible value in quotes.
Related
I've been scratching my head on the best way to accomplish this.
I'm getting 8 variables from a url:
a=imagine
b=lead
c=champion
d=champion
e=champion
f=champion
g=lead
h=champion
In this example there's 5 "champion" so I'd redirect to my champion page.
I've added them into an array:
$a = $_GET["a"]; $b = $_GET["b"]; $c = $_GET["c"]; $d = $_GET["d"]; $e = $_GET["e"]; $r = $_GET["r"]; $g = $_GET["g"]; $h = $_GET["h"];
$info = array($a,$b,$c,$d,$e,$f,$g,$h); print_r(array_count_values($info));
and then printed: Array ( [imagine] => 1 [lead] => 2 [champion] => 5 )
Am I doing it right? How can I use those values to redirect to my champion page as that's the highest count?
First, I agree that array_count_values is a good tool for this, but you don't need to make a new array with all the $a, $b, etc. variables. You can just do
$info = array_count_values($_GET);
After you have that, you can sort the array in descending order and take the first key to find the page you want to redirect to.
arsort($info);
$location = key($info);
I agree with the other answer that redirecting to a page based on user input is risky, and you should not redirect without first verifying that the location is valid. If you only have a few valid locations, this could be as simple as:
if (in_array($location, ['champion', 'lead', 'imagine'])) {
header("Location: yourdomain/$location");
}
If I understand you correctly:
$list = ['imagine' => 1 ,'lead' => 2, 'champion' => 5 ];
// find the highest count
$highest = max($list);
// check what page it is
foreach($list as $page=>$count){
// redirect
if($count === $highest){
header('Location: ' . $page);
exit();
}
}
Beware that relying on the user input is not safe. I'd also look up a white list for the pages.
Well, after I rewrote my problem description 2 times i'll do it somehow less abstract now.
I need a way to return data within an array so that this array accepts this returned data as native key / value pair.
Illustration:
simple array:
$a = array('a' => 'b');
I could access the value of 'a' by simply calling $a['a']... clearly
I now need a way to exactly get this result via a function call or hack or something!
something like
$a = array(foo('a','b'));
the problem is, when "foo" return an array, the structure of my $a (array) will look like this:
array(array('a','b')) and not like array('a' => 'b')
and will prevent me from being able to access the data via $a['a']
The reason I need this is that I instance objects on demand within this array definition and also modify these instances on the fly, but I do need 2 different returns (of functions) of one and the same object and don't want to copy past half the initialization. Further more I don't want to first declare object instances outside the array because this would be a absolute overkill and would perfectly destroy all readability.
So.. is there a possibility to extract returned values to native language features?
PS. I also don't want to iterate over the array to re-process the data
$a = foo('a','b');
with
function foo($x,$y) {
return array($x => $y);
}
If foo() is returning an array, why not;
$a = foo('a','b');
Seems simple enough, right?
Easiest way:
$a[]= foo();
function foo() {
return array(1,2);
}
Or use reference:
$value = NULL;
$a = array(foo($value), $value);
with
function foo(&$value) {
$value = 'b';
return 'a';
}
function foo($key) {
$r = array(
'a' => 'b',
$key2 => $value2,
$key3 => $value3,
$key4 => $value4
// ...
);
return $r[$key];
}
$a = foo('a'); // means $a = 'b';
Do it solves your problem ?
I have this code for my school project and thought the code does its job on what i wanted it to do, i still keep on getting the error about $_SESSION[] is not an array argument when using the array_replace() and array_merge() functions:
Session is already initiated on the header:
// Start Session
session_start();
For initialising the $_SESSION['cart'] as an array:
// Parent array of all items, initialized if not already...
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
For adding products from a dropdown menu: - (Just to see how the session is assigned:)
if (isset($_POST['new_item'])) { // If user submitted a product
$name = $_POST['products']; // product value is set to $name
// Validate adding products:
if ($name == 'Select a product') { // Check if default - No product selected
$order_error = '<div class="center"><label class="error">Please select a product</label></div>';
} elseif (in_array_find($name, $_SESSION['cart']) == true) { // Check if product is already in cart:
$order_error = '<div class="center"><label class="error">This item has already been added!</label></div>';
} else {
// Put values into session:
// Default quantity = 1:
$_SESSION['cart'][$name] = array('quantity' => 1);
}
}
Then here is where the issue comes, when they try to update the product:
// for updating product quantity:
if(isset($_POST['update'])) {
// identify which product to update:
$to_update = $_POST['hidden'];
// check if product array exist:
if (in_array_find($to_update, $_SESSION['cart'])) {
// Replace/Update the values:
// ['cart'] is the session name
// ['$to_update'] is the name of the product
// [0] represesents quantity
$base = $_SESSION['cart'][$to_update]['quantity'] ;
$replacement = $_SESSION['cart'][$to_update] = array('quantity' => $_POST['option']);
array_replace($base, $replacement);
// Alternatively use array merge for php < 5.3
// array_merge($replacement, $base);
}
}
Note that both the functions array_replace() and array_merge() are updating the values and doing what the initial goal was, but the problem is that i still keep on getting that one argument($base) is not an array issue.
Warning: array_replace() [function.array-replace]: Argument #1 is not an array in ...
any suggestions for a better way to approach this issue would be a valuable help :)
Thanks for your help :)
Edit: The in_array_find() is a function that i use in replacement of in_array() as it doesn't apply to finding values in a multi-dimensional array: specifically 2 depth arrays:
found it from here and it works for me
The code for it is:
// Function for searching values inside a multi array:
function in_array_find($needle, $haystack, $strict = false) {
foreach ($haystack as $item => $arr) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
array_replace returns the replaced array. So you need to do:
$base=array_replace($base, $replacement);
Also, I suggest using named keys consistently throughout, as opposed to mixing named and numeric:
$base = $_SESSION['cart'][$to_update]['quantity'];
EDIT:
This may not be exactly what you're going for...
I set up a test situation without using $_SESSION, and I got the same error you did. I changed the code as follows and no longer get the error.
$sesh=array(
'cart'=>array(
0=>array(
'quantity'=>1
)
)
);
$to_update=0;
$new_quantity=5;
//$base = $sesh['cart'][$to_update]['quantity']; <--- changed this to line below
$base = $sesh['cart'][$to_update];
$replacement = $sesh['cart'][$to_update] = array('quantity' => $new_quantity);
$base=array_replace($base, $replacement);
echo"<pre>";print_r($base);echo"</pre>";
PHP FIDDLE: http://phpfiddle.org/main/code/mvr-shr
This have solved this issue:
Basically as per the structure: (Lets slice it into bits)
$_SESSION['cart'] = array();
then
$_SESSION['cart'][$name] = array('quantity' => 1);
finally:
$base = $_SESSION['cart'][$to_update]['quantity'] ;
$replacement = $_SESSION['cart'][$to_update] = array('quantity' => $_POST['option']);
array_replace($base, $replacement);
The reason why it says that the argument $base is not an array is because:
['quantity'] in $base is not an array as it forms the 'quantity' => 1 what we need is the array() value from the array('quantity' => 1); for it to be identified as an array.
So final answer should be: $base = $_SESSION['cart'][$to_update];
as there is only one array() recorded in where the $to_update resides so the replacement argument shall replace this identified array.
$_SESSION only exists when a Session starts. In order to do that you need to add on top of all your code session_start() otherwise the session will not start, unless you define it on php directives.
People
I am trying to build a shopping cart, So i will have to pass the id , quantity and location_id to the function. In the function, i will look at the id and location_id passed in, if similar id and location_id is found. I will +1 to the item. However, if i use the function in array, it is not working.
Below is another function i built to test the variables pass to function within foreach.
But is does not say the first variable i passed in. it will only save the latest variable.
Below is my function codes :
static public function test($id , $per_min, $location_id_cart = 0){
echo $new_cart = $id.'-'.$per_min.'-'.$location_id_cart;
if(isset($_COOKIE['cart_item'])){
$last = $_COOKIE['cart_item'];
$testing = $last.','.$new_cart;
}else{
$testing = $new_cart;
}
$set = setcookie("cart_item", $testing, time()+3600);
var_dump($_COOKIE);
}
Below is my codes calling the function :
$id = 125;
$multi_location = array(636 , 789);
$multi_quantity = array();
$multi_quantity[636] = 5;
$multi_quantity[789] = 10;
$array_key = array_keys($multi_quantity);
foreach($array_key as $o){
if(!in_array($o , $multi_location)){
unset($multi_quantity[$o]);
}
}
$count = 0;
foreach($multi_location as $i){
ZCart::test($id , $multi_quantity[$i], $i);
}
My result :
'cart_item' => string '125-10-789' (length=10)
My expected result :
'cart_item' => string '125-5-636,125-10-789'
if i refresh my page, the result i get is this :
'cart_item' => string '125-10-789,125-10-789,125-10-789,125-10-789,125-10-789,125-10-789,125-10-789'
The cookie will only save the latest value given in the array. it does not save 125-5-636 to the cookie.
Why? can anyone help me on this please? Thank you!
try the following code:
static public function test($id , $per_min, $location_id_cart = 0){
$new_cart = $id.'-'.$per_min.'-'.$location_id_cart;
if(isset($_COOKIE['cart_item'])){
$last = $_COOKIE['cart_item'];
$testing = $last.','.$new_cart;
}else{
$testing = $new_cart;
}
$set = setcookie("cart_item", $testing, time()+3600);
//This line deals with adding to the cookie while the script is running
$_COOKIE['cart_item'] = $testing;
//var_dump($_COOKIE);
}
I have a feeling that the $_COOKIE array isn't being updated when you use setcookie(), this is why we update it manually with the line below it.
Also I'd remove the var_dump() call, along with echoing the $new_cart variable, as this will stop setcookie() from working. Instead, I would put it at the bottom of your calling code:
$id = 125;
$multi_location = array(636 , 789);
$multi_quantity = array();
$multi_quantity[636] = 5;
$multi_quantity[789] = 10;
$array_key = array_keys($multi_quantity);
foreach($array_key as $o){
if(!in_array($o , $multi_location)){
unset($multi_quantity[$o]);
}
}
$count = 0;
foreach($multi_location as $i){
ZCart::test($id , $multi_quantity[$i], $i);
}
var_dump($_COOKIE);
If you are implementing a shopping cart, I'd strongly recommend using sessions, which allow you to store the sensitive stuff on the server side away from harm and are in my experience much easier to work with than cookies!
Another option would be to store the user's cart in a database and then if they aren't logged in link to that cart with an ID stored in a cookie. This would allow the cart to stay around if the user closes their browser but keeps the secure stuff from the cookie. I hope this makes sense!
because you are not using array or different variable. Every time you call function in loop, It updates value of cart_item.It doesnot store value in different variables.
$_GET variable cannot identify the first array element.:
I have passed an array in url which looks like this
http://www.example.com/form.php?action=buy_now&ft=prf&Arrayproducts_id[]=431&products_id[]=432&Arraycart[]=1&cart[]=3&Arrayid[]=431&id[]=432
but when i print the array "products_id" and "cart" by using print_r($_GET), it just display me
Array
(
[0] => 432
)
Array
(
[0] => 3
)
now as u can see the url it also contains the value "431" for products_id and "3" for cart
I can see that due to the string "Array" appended to these they are not being accessed, So could someone suggest me how to fix this issue
EDIT as per Felix review
for($t=0;$t<4;$t++){
$proid_30 .= "products_id[".$t."]=".$products_id."&";
$bucket_30 .= "cart[".$t."]=".$_SESSION['qty_flex'][$t]."&";
$idproid_30 .= "id[".$t."]=".$products_id."&";
}
$idproid_30.=" ";
$idproid_30 = str_replace("& ","",$idproid_30);
echo "<script>window.location= '/print_ready_form.php?action=buy_now&ft=prf&".$proid_30.$bucket_30.$idproid_30."&osCsid=".$_GET['osCsid']."';</script>";
Looks like you echo an array to create your URL. This does not work:
$a = array(1,2);
echo $a;
prints
Array
Can you show the PHP code that generates the URL?
Update:
Without more code I can only assume, but I think that $proid_30, $bucket_30 and $idproid_30 are initialized as arrays. Now when you append a string, they are casted to strings:
$a = array(1,2);
$a .= 'test';
echo $a;
prints
Arraytest
Use new variables to build the URL or initialize them as strings:
E.g.:
$product = '';
$cart = '';
$id = '';
for($t=0;$t<4;$t++){
$product .= "products_id[".$t."]=".$products_id."&";
$cart .= "cart[".$t."]=".$_SESSION['qty_flex'][$t]."&";
$id .= "id[".$t."]=".$products_id."&";
}
you can use variable names like "var[]" in a http form. do you need to use only get method? try post
Its only displaying the 432 for products_id because the only other products_id in the link is called Arrayproducts_id.
You will need to rename this back to products_id =)
Unless you want to call Arrayproducts_id ofcourse.
First product Id was named as "Arrayproducts_id". So you can get by printing "Arrayproducts_id"