php - Storing multiple values in $_SESSION array
I am new to php and this issue is bugging me sincelast one day. I have three pages, 1. classpage.php ---- which holds,
<?php
session_start();
class addStock{
public function storeSessArray($stk_code){
array_push($_SESSION['recentlyView'],$stk_code);
}
}
?>
- logic.php---which holds,
$_SESSION['recentlyView']=array();
$checkSession = new addStock;
$chkSession = $checkSession->storeSessArray($val);
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>
and 3. front.php which holds
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title Page</title>
</head>
<body>
<?php
$val='5';
?>
<?php
include 'logic.php';
?>
</body>
</html>
I want to keep an array of values stored in$_SESSION['recentlyView']
array when someone loads front.php. But each time I assign a different value to $val, only the last value which was stored in $val appears in$_SESSION['recentlyView']
array. I want each of the value that was used in$val
to be stored in$_SESSION['recentlyView']
Answer
Solution:
Likely you keep overwriting the session array. Try checking if it’s set already:
This will only set the array once, then your method will just add to it.
Also, as noted in the other answer, make sure to put the
session_start();
in the most top-level page at the very beginning.Answer
Solution:
try this, it should solve your problem.
class addStock{
}
Answer
Solution:
You must call
session_start()
before there is any output. The documentation notesAs you've presented your code, the very first thing that is loaded is
front.php
which includeslogic.php
which calls the class inclasspage.php
. (I don't see how that page is referenced-- whether it is by include or spl.You've got the right idea in separating your presentation from the logic, but you've got the order backwards. The very first thing that needs to happen is the execution and loading of relevant php code, with presentation being the very last thing that happens. Unfortunately the very first things that happens in your script is it immediately starts output.
The solution is to funnel all requests through index.php (look up how to do seo-friendly urls), and from there use a "front controller" or "router".
Short of that, you need to include a brief php section on top of front.php, so that session start is called before output.