How to add and access array from session in PHP - php

I am new with php. I want store multidimensional associative array in session and also fetch the value of array from session. But I am not able to do this properly.
Below is my code. Thanks.
$myArray = array();
if ((!isset($_SESSION['game']))) {
echo 'the session is either empty or doesn\'t exist';
} else {
$myArray = unserialize($_SESSION['game']);
}
array_push($myArray, new MapResult($keyId, $colorCode, 'NP', $highlow, 'NP', $evenOdd, 'NP'));
session_start();
$_SESSION['game'] = serialize($myArray);
?>

You can't access $_SESSION variables before calling session_start. Also, your serializing of the data is probably pointless. Session data is stored server-side. Serializing would be used if you wanted to dump the session state to a file or to a database or something.
A word of advice...
Instead of littering your code with $_SESSION references, it helps to wrap access in reusable functions. Your code will look nicer and you'll be free to change how session data is stored/accessed at any time without having to refactor your entire app.
// must be called before reading/writing $_SESSION
session_start();
function session_is_initialized() {
return isset($_SESSION['game']);
}
function session_setup() {
$_SESSION['game'] = [/* some initial data */];
}
function session_add_item($item) {
array_push($_SESSION['game'], /* more data */);
}
Now you can write nice clean code
if (!session_is_initialized()) {
session_setup();
}
session_add_item(['some', 'data']);

Related

How to Hide URL parameters with php redirect

I read this article: http://smallbusiness.chron.com/hiding-url-parameters-php-redirect-33163.html
which explains how to but I'm don't understand how you redirect with the header as they say in there.
For storing in sessions this is code I use
session_start();
function input_val($key, $remember = true) { //use input_val('nameofinputfield')as value to be able to store in session
$value='';
if(isset($_REQUEST[$key])) {
$value = $_REQUEST[$key];
//Store value in session if remember = true
if($remember) {
$_SESSION[$key] = $value;
}
return $value;
} else {
//Return session data
return isset($_SESSION[$key]) ? $_SESSION[$key] : $value;
}
}
Let's say, you want to pass a username and email parameter from your script1.php to script2.php. If you are using POST method, in the URL the parameters won't show, and you can access your passed variables through $_POST global variable. But, if you want to use GET method for any reason, or you want to store data in $_SESSION you can do this.
You can try to use this in your script2.php:
session_start();
if (count($_GET)) {
foreach ($_GET as $key => $value) {
$_SESSION[$key] = $value;
}
header("Location: " . $_SERVER["PHP_SELF"]);
}
//At here, you can access all of your parameters from $_SESSOION variable
var_dump($_SESSION);
I will try to explain it as simple as I can, it's not that difficult.
When a user is in a session with the php he stores a little blob of text in the browser, this text is like a user ID that lasts until he close his browser. The php script can tell and extract information from the server, like parameters, by knowing his ID. This is not a cross-server feature though and it isn't persistent, unlike cookies, the expiration on the sessions are normally short and they expire when the user closes his browser.
Also it is recommended not to use it to store Get information like Page number, because it can't be re-referenced.

Close session without writing or destroying it

Is there a way to close a PHP session without either writing or destroying it? Am I missing something or are there just two functions (session_write_close() and session_destroy()) which reset session_status() to PHP_SESSION_NONE? In other words, if I have an open session, can I simply close it without affecting the external session data, so it can be reloaded again.
You can do this by $_SESSION = null. The session is unavailable but the data remains (does not get deleted).
Consider you have data in the session:
<?php
session_start();
session_regenerate_id(); // get a fresh id
echo session_id();
$_SESSION['test'] = '12345';
print_r($_SESSION); // echoes the data in the session
Data: test|s:5:"12345";
Then in the next request:
<?php
session_start();
echo session_id() . "<br>"; // echoes the same id as of the last request
$_SESSION = null;
print_r($_SESSION); // echoes nothing
echo "<br>";
echo session_status(); // echoes 2 (PHP_SESSION_ACTIVE)
Data still the same: test|s:5:"12345";
(php-fpm 5.4.29, most recent nginx, memcached as session handler).
Well the data still can be written through $_SESSION['whatever'] = ... but not read. I'm not sure whether this is a good solution but I have to admit I still don't understand why or whatfor you need this.
As an alternative, you could implement a wrapper class for the session with a property $this->active = true; // or false:
class MySessionWrapper {
protected $active;
protected $data;
// getter setter for $this->active and $this->data ...
public function getData($var) {
if ($this->active !== true) {
throw new Exception('session disabled');
}
}
}
Some months later after raising an issue the two new methods are now available in PHP 5.6, but the documentation arrived only with 5.6.2.
session_abort() – Discard session array changes and finish session, see the docs.
session_reset() – Re-initialize session array with original values, see the docs.

File session: is it always generated?

Does Php always create a session file as soon as session_start() is called, even though there's nothing to keep track of (= no variable written in $_SESSION[])? If so, why?
Default PHP file-based sessions encode the session ID into the session file's filename. Since that's the only place the ID is kept normally, SOMETHING has to be kept to store the id. That means you'll get a file created, even if nothing is EVER written to $_SESSION.
In PHP-like pseudo code, basically this is occuring:
function session_start() {
if (isset($_COOKIE[ini_get('session.name')])) {
// session ID was sent from client, get it
$id = $_COOKIE[ini_get('session.name')];
} else {
// no session ID received, generate one
$id = generate_new_id();
setcookie(ini_get('session.name'), $id, ......);
}
$session_file = ini_get('session.save_path') . '/sess_' . $id;
if (file_exists($session_file)) {
// found a session file, load it
$raw_data = file_get_contents($session_file);
$_SESSION = unserialize($raw_data);
} else {
// brand new session, create file and initialize empty session
file_put_contents($session_file, serialize(array());
$_SESSION = array();
}
// lock the session file to prevent parallel overwrites.
flock($session_file);
}

Temporary array?

It's a long story that I'm fighting with, so I'm not going to extend to much for now, but and if not possible I will detail the problem.
I'm using Laravel framework. From an ajax call I send data from an upload form (plupload) to a function inside a controller.
Let's say I have the following functions in my controller:
function action_tempupload()
{
$temp = array();
$temp[] = Input::all();
return true;
}
function action_upload($news_id)
{
global $temp;
$input = $temp;
echo "<pre>";
//print_r($news_id);
print_r($input);
echo "</pre>";
exit();
}
function action_save($parameters = array())
{
// create news record in database and
// have a variable containing the news id sent to:
$this->upload($mysql->news_id);
}
Is it possible to have an temporary array, that saves each POST of the form for the image upload and call the array later in another function?
If they're are separate requests, then you can just store the array in a $_SESSION and unset all the created sessions in the last action method.
Click on the link of you need to know more about $_SESSIONS. The usage is pretty straight forward.

PHP Sessions problems

I'm working with a third party COM object from PHP and I want to save the object on a session variable to access it in future server calls.
If I save the object in session:
$_SESSION['collItem'] = $collItem;
I can access it's methods and properties through $_SESSION['collItem'] inmediately after definition.
But, in future calls to server, if I try to use $_SESSION['collItem'], I can't access it again.
I write here some more code to clarify.
Method to initailize COM object in my script "functions.php":
public function setAppData() {
try {
$appD = new COM('ASData.CASDataApp');
$appD->InitMasterData(true, 1, 91);
$appD->DateMask = 'ymd';
$_readDB = $appD->InitApp($this->readDB());
} catch (Exception $e) {
$err = 'Connection error: ' . htmlentities(addslashes(strip_tags($e->getMessage())));
$this->setError($err);
return false;
}
$appD->appPath = str_replace('\app\include', '', __DIR__);
$this->iniciarCollections($appD);
$this->appData = $appD;
}
Call to method from my script "edit_json.php":
require_once('functions.php');
if (!session_id()) {
session_start();
}
// We recover $mbw object saved in session and initialize COM object
if (isset($_SESSION['mbw'])) {
$mbw = unserialize($_SESSION['mbw']);
}
$mbw->setAppData();
$appData = $mbw->getAppData();
$_SESSION['appData'] = $appData;
If I try access $_SESSION['appData'] inmediately after COM initialization I can work with it without problems, but if I try next code in future server calls (whith $appData object saved in $_SESSION['appData']:
if (!session_id()) {
session_start();
}
$appData = $_SESSION['appData'];
// I can't work with $appData object if I don't initialize it again
Reinitializing COM object isn't a good solution for me because I lose all changes I made.
Use session_start() at the beginning of your script. You need it to retrieve session data from the server into the $_SESSION variable.
From http://php.net/manual/en/function.session-start.php :
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
You should edit your question and include your getAppData() method, as well, so we can do a better diagnostic. But what I can guess is that your getAppData() returns an object, and, in that case, when you have a code like
$appData = $mbw->getAppData();
$_SESSION['appData'] = $appData;
what PHP is doing is saving in $_SESSION['appData'] only a reference to the $mbw->getAppData() object, and not the real object.
If you want to store the real object in session, you would have to do the following:
$_SESSION['appData'] = serialize($appData);
and then, whenever you want to use the stored object, you would do:
if (isset($_SESSION['appData'])) $appData = unserialize($_SESSION['appData']);
on the beggining of every file that uses the $appData that was saved in the session.

Categories