Home > Net >  session varaiable name as a variable?
session varaiable name as a variable?

Time:02-01

I try to make a session variable where the session variable name should be diffrent, and therefore i make the session variable name a variable name:

$nummer = $_POST['nummer'];
$num = $nummer; 

$vareInfo = array(
    "vareNummer" => "$nummer",
    "vareNavn" => "$vare",
    "varePris" => $pris, 
    "vareBillede" => $VarBillede, 
    "vareAntal" => $antal
);
$_SESSION[$num] = $vareInfo;
$_SESSION[$pris] = "hukabuka";

but i dosen't work, i just changeching the the other sessioen to the new value?

it output this:

Array ( [vareNummer] => 182162 [vareNavn] => Solsikke [varePris] => 120 [vareBillede] => 63c7cba6cac6d7.24544415.jpg [vareAntal] => 1 )

and next time i run it it changing it instead of making a new

CodePudding user response:

To prevent that your session gets overwritten add a check if the session already exists.
That way it only gets created once for each unique $num

$nummer = $_POST['nummer'];
$num = $nummer; 

$vareInfo = array(
    "vareNummer" => "$nummer",
    "vareNavn" => "$vare",
    "varePris" => $pris, 
    "vareBillede" => $VarBillede, 
    "vareAntal" => $antal
);
if(!isset($_SESSION[$num])){
  $_SESSION[$num] = $vareInfo;
}
if(!isset($_SESSION[$pris])){
  $_SESSION[$pris] = "hukabuka";
}

CodePudding user response:

you can make session read only as well to prevent from writing

<?php 
session_start();
$nummer = $_POST['nummer'];
$num = $nummer; 

$vareInfo = array(
    "vareNummer" => "$nummer",
    "vareNavn" => "$vare",
    "varePris" => $pris, 
    "vareBillede" => $VarBillede, 
    "vareAntal" => $antal
);
$_SESSION[$num] = $vareInfo;
$_SESSION[$pris] = "hukabuka";
session_write_close();
?>
  • Related