I've got this session variable, which was initiated in index.php
<?php
$sid = session_id();
if (empty($sid) {
session_start();
}
//value of the variable can be changed and saved before coming back to the index
if(!isset($_SESSION['context'])){
$_SESSION['context'] = 1;
}
//...
?>
Later a script is used to create or update a database entry.
entryupdate.php:
<?php
include_once("template.php");
/*....*/
$sid = session_id();
if (empty($sid)) {
session_start();
}
/*....*/
//Create a new entry, context is not given in the $input_object at this point.
$template = new Template($input_object);
$context = $template->getContext();
?>
template.php is a script where only the Template Object is defined, so I don't call $session_start in it, my rationale being that it would always be called by the scripts including it, as it is in the case I'm describing here. Here is the relevant code:
<?php
class Template
{
private $m_context;
//other private parameters
function __construct($arguments_object){
if(!is_null($arguments_object)){
/*....*/
$this->m_context = $arguments_object->context;
/*....*/
}
}
/*....*/
function getContext(){
if(!empty($this->m_context)){
return $this->m_context;
}else{
//this would be our case, as the parameter was not initialized yet.
return $_SESSION['context'];
}
}
/*....*/
}
?>
Now, a colleague stumbled on an error and upon investigation, I found out that the $context was set to NULL. When I tried to reproduce the issue, the context was correctly initialized. And to be honest, for the few years the tool has been used, it is the first time this kind of issue was encountered.
I've also checked, at no point I am unsetting this particular session variable.
Am I making a false assumption there, in thinking that template.php would find the session variable when the session was started in entryupdate.php where it was included and used?
Related
The session I set is lost after the form is submitted.
I had built the session class to set new session, unset and so on. In function.php of wordpress template.
function.php
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
Session.php
class session {
function __construct() {
}
function set_flashdata($name, $value) {
$_SESSION[$name] = $value;
}
function flashdata($name) {
if (isset($_SESSION[$name])) {
$str = $_SESSION[$name];
return $str;
} else {
return FALSE;
}
}
function userdata($name) {
if (isset($_SESSION[$name])) {
return $_SESSION[$name];
} else {
return FALSE;
}
}
function set_userdata($name, $value) {
$_SESSION[$name] = $value;
}
function unset_userdata($name) {
if (isset($_SESSION[$name])) {
unset($_SESSION[$name]);
}
}
}
I try to set session as :
<?php
$sess = new session();
$sess->set_userdata('sess_name',"some value");
?>
<form action="get_permalink(212);">
//input buttons
</form>
After submit the form it goes to the permalink(212). Then I tried.
<?php
$sess = new session();
$value = $sess->userdata('sess_name');
var_dump($value); //returns false. That means session is lost after form submit. Why?
?>
You need to move session start/resume into your Session's constructor.
Like so:
class session
{
function __construct()
{
if (! session_id()) {
session_start();
}
}
Another thing to mention, every time you'll do new Session you'll be getting an object of the same functionality working with same global variable $_SESSION.
You don't need more than one $session object, it would be a good time to look into Singleton pattern.
You have to call always session_start() for each request.
The mission of session_start() is:
Creates a new session
Restart an existing session
That means, if you have created a session, and you don't call to the method session_start(), the variable $_SESSION is not going to be fulfilled.
Except: If in your php.ini you have set the option session.auto_start to 1, then, in that case it is not needed to call the session_start() because the variable $_SESSION is fulfilled implicitly.
You need to use wordpress global variable for condition that session is set or not something like :
global $session;
if (!session_id()) {
session_start();
}
include get_template_directory() . "/custom/session.php";
It might be due to www. at the start of your website domain. Make sure that both of pages use the same structure.
Also I faced with the same issue long time ago when the form sends the data to a secured address (https://)
I hope these two items may help you.
Sounds to me like session_start() is not set at the start of the page that get_permalink(212;) refers to.
I have almost no experience with WP itself though, so I might misunderstand the functionality of get_permalink()
I agree with the answer from #rock3t to initialize session in constructor of class, but every time a class object is initiated, it will go to check for session!
Instead, if you are fine, the simplest way to get access to session is by adding following lines to your wp-config.php file before the call to wp-settings
if (!session_id())
session_start();
This will set/initialize session globally and you won't need to set/check for session_start in constructor of a class.
Thank you.
i have a problem calling a session variable from another script. can anybody help me on this matter.
Below is the script that i create the session and store the time in a session variable.
<?php
session_start();
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Here is the script that i try to access this session variable from a function of it. till now nothing worked
<?php
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
this hasnt worked upto now, nothing prints...can anybody give tips to sought this out and its compulsory to have this function timeofclick
You're not creating your class on your second file add:
//I don't know what this does but if it already starts a session remove the session start inside the class.
include '../../mydomain/myscript.php';
$survey = new survey_Tracksciprt();
$survey::timeofclick();
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
I also advice putting session_start at the top of your file.
<?php
session_start();
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
Always use the session_start(); at the top line of the page.
First, you need an init-session.php file, containing:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Second, you need to include this file at the start of your loader/layout (whatever you have there), so no operation will be executed before you initialize your session.
Third, you should initialize $orgtimestamp like this:
<?php
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Fourth, you need to call survey_Tracksciprt::timeofclick().
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.
I defined a session class,which uses values from the $_POST variable in an array called $sessionVars. When a user logs-in a new instance of the session class is created, a construct function sets session variables.I checked that this is working correctly.Problem: When i try to access those variables from a different page the session shows that its not started and those variables are undefined. Confused cause I thought $_SESSION being a super global means its accessible all the time(i.e scope doesn't matter) . I suspect im doing something wrong when I try to access the $_SESSION variables since they are in a class. I appreciate any help..thanks in advance.
class userSession{
public function __construct($sessionVars){
session_start();
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
/*just for housekeeping. not used in application*/
function showvars(){
echo $_SESSION['userEmail'].'<br><br>';
echo $_SESSION['userID'].'<br><br>';
echo $_SESSION['userFolder'];
$sessionID=session_id();
echo '<br><br>'.$sessionID;
}
}//**END USER SESSION
/*This is the login script that calls the session*/
include 'library.php';
$show=new render;
$show->index();
if(!isset($_POST['login']) ){
$show->usrLogin();
} else{
if(!empty($_POST['email'])){
$postVars=array('user'=>$_POST['email'],'pass'=>$_POST['password']);
$user=new user();
$data=$user->loginUser($postVars);
$currSession=new userSession($data);
}else{
die('No data in POST variable');}
}
/*file upload that needs the session[userFolder] variable*/
function file_upload(){
$userFolder=&$_SESSION['userFolder'];
echo '<hr>userFolder is : '.$userFolder;
function do_upload(){
if(!empty( $_FILES) ){
echo $userFolder.'<hr>';
$tmpFldr=$_FILES['upFile']['tmp_name'];
$fileDest=$userFolder.'/'.$_FILES['upFile']['name'];
if(move_uploaded_file($tmpFldr,$fileDest)){
echo 'file(s) uploaded successfully';
}
else{
echo 'Your file failed to upload<br><br>';
}
return $fileDest; //returns path to uploaded file
} else{die( 'Nothing to upload');}
}//END FUNCTION DO_UPLOAD,
/*Perform upload return file location*/
$fileLoc=do_upload();
return $fileLoc;
}
You need to instantiate an object of this class on every page that uses the session (or start the session manually). Also, you'll not want that constructor, instead some other way of setting vars. This is just for illustration of how it works with your current code, there are much better approaches:
class userSession {
public function __construct(){
session_start();
}
function set_login_vars($sessionVars){
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
}
//page1.php
$session = new userSession;
$session->set_login_vars($loginVars);
//page2.php
//you need to start the session, either with the class
$session = new userSession;
//or session_start();
print_r($_SESSION);
I'm trying to implement and authentication system with jQuery and PHP. All the php work is made in the controller and datahandler class. There is no php code inside the .html files, all the values in .html files are rendered via jQuery that request the data from php server. So what I'm trying to do is:
When user clicks the login button, the jQuery makes a call to the authenticate() method in my controller class, it checks if the user is correct and stuff, and if it is, start the session and set the user_id on the session so I can access it later, and returns the userId to the jQuery client again.
After that, if everything is fine, in jQuery I redirect it to the html file. On the html file I call a jQuery from the <script> tag that will handle other permissions. But this jQuery will access the method getPermissionString (from the same class of authenticate() method mentioned before), and it will need to get the session value set in authenticate method.
The Problem:
When I try to get the session value inside getPermissionString() it says:
Notice: Undefined variable: _SESSION
I've tried to check if the session is registered in the second method, but looks like it's not. Here is my PHP code.
Any idea? Thanks.
public function authenticate($login, $password)
{
$result = $this->userDataHandler->authenticateUser($login, $password);
if(is_numeric($result) && $result != 0)
{
session_start();
$_SESSION["uid"] = $result;
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
echo $result;
}
else
{
echo 0;
}
}
public function getPermissionString()
{
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
Before you can access $_SESSION in the second function you need to ensure that the program has called session_start() beforehand. The global variable is only populated when the session has been activated. If you never remember to start a session before using it then you can change the php.ini variable below:
[session]
session.auto_start = 1
Further, you said that you're using a class for your code. In this case you can also autos tart your session each time the class in created by using magic methods:
class auth {
function __construct() {
session_start();
}
function yourfunction() {
...
}
function yoursecondfunction(){
...
}
}
If you don't have session.auto_start enabled, and authenticate and getPermissionString are called on two different requests, you need to call session_start() in each function.
If you need more information on how the session ID is passed, just read Passing the Session ID
You should not use that function if session is not started. So throw an exception:
public function getPermissionString()
{
if (session_status() !== PHP_SESSION_ACTIVE)
{
throw new Exception('No active session found.');
}
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
This ensures the pre-conditions of your functions are checked inside the function so you don't need to check it each time before calling the function.
You will now see an exception if you wrongly use that function and it will give you a backtrace so you can more easily analyze your code.
For php sessions to work you have to call session_start() every time you script is requested by the browser.