How to set unset session variable back? - php

I'm trying to test my php script, so I need to (at least temporarily) get back some of the unset variables.
I mean:
page1.php:
<?php
session_start();
$_SESSION['var']="somevalue";
go_to("./page2.php");
?>
page2.php:
<?php
session_start();
use($_SESSION['var']);
unset($_SESSION['var']);
?>
Now when I go to page1->page2, then page1 again (then page2 again) page2 does not recognize $_SESSION['var'], so I need something like
if(!isset($_SESSION['var']))
{
set_back($_SESSION['var']); //But how ?
}
in page1.php.
Any help would be appreciated. Thanks!

I think that your problem is the local browser cache.
When you go back to page1 the response is served from your computer cache instead from the server so the session variable is not set again

There is no functionality in php that "rolls back" a session/variable that has been unset (Of course you could store the original value in temporarily session like Boaz suggested). What exactly are you trying to achieve?

Related

What can destroy a $_SESSION variable php?

I am working on a webapp in php, and my session keeps getting destroyed on only certain views of my application and I can't seem to find out why. I can't upload all the code here because there is too much, so I want to know what can destroy a session and I will look for the problem.
The weird part is that it happens inbetween two views, for example it fully loads the first view with no problem (I checked with echo statements at the end of that view to make sure it was still active) and when I click on a link the session variable is destroyed before loading the next view.
if it happened only on certain view, is there any session unset or session destroy? and maybe you need to add session_start() on controller which have those view (linked). (read also https://www.sitepoint.com/php-sessions/ about session_start section )
You can destroy ALL the session array :
session_destroy();
Or only unset some parts :
unset($_SESSION('your_thing']);
An other way is to put empty some parts of the array:
$_SESSION['your_thing'] ='';
All are correct, but if you destroy all the session, on the next page you have to set session_start(); if you want use session, but you 'll lose all informations.
the best way is to use unset or empty the array ...
You can use the session_destroy();-function to destroy the whole session (and all $_SESSION-values with it) or you can the unset-function to destroy a value by key as if $_SESSION was an array.
Make always sure you're using session_start() the right way. On top on every page you are using the sessions. The session keeps destroying because the session was never made. To make it work, be sure you have set up the session start like this example:
<?php
session_start(); // Be on top
?>
<!DOCTYPE html>
<!-- The rest of your page
I hope this will help you

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

PHP - $_SERVER['HTTP_REFERER'] - how to store once, not again when a form submission occurs

In PHP, how would I go about storing the variable "backurl"? (retrieved as shown below at the bottom - when the following constraints need to apply)
The variable "backurl" is storing the last php script viewed.
On first execute the variable "backurl" is stored and works correctly
When a form is submitted through $_GET or $_POST within that script, the variable will update as the previous URL has changed. (I don't want this to happen)
i.e.
FROM -> TO (actual outcome - desired outcome)
page1.php -> page2.php (link goes to page1.php - as intended)
page2.php -> page2.php?test=yes (link goes to page2.php - I want it to go back to page1.php)
If anyone has any suggestions of how to do this, thank you very much!
$backurl = $_SERVER['HTTP_REFERER'];
you could use sessions
<?php
session_start();
if(!isset($_SESSION['backurl'])){
$_SESSION['backurl'] = $_SERVER['HTTP_REFERER'];
}
?>
$_SESSION['backurl']; //contains the back url;
and if you nee to unset the backurl:
unset($_SESSION['backurl']);
Set the backurl in session and access it whenever & however you needed in page2.php
There are several ways to do this. One could be updating your backurl only if the script page is different, using session.
e.g. (untested):
session_start();
if( $_SEVER['SCRIPT_NAME'] != $_SESSION['lastpage'] ){
$_SESSION['backurl'] = $_SERVER['REQUEST_URI'];
}
This way, you'll only update the backurl when you call a different php page, leaving it unchanged when you go to the same page with different parameters (based on your example).
Adapt the code to your needs.

PHP Session ID the same but variables are lost

I have a login page that sets session variables upon successful login. The login page then redirects to an admin page. The admin page is able to read session variables just fine. But when I do a jQuery load() function that loads viewUsers.php in the content div the session variables are gone. The weird part is the session id is the same.
I used var_dump() on both the admin page and the viewUsers page. The admin pages shows all the proper variables from the login page but the viewUsers page which is called with a jQuery load() function var_dump of $_SESSION is blank. var_dump of $_COOKIE['PHPSESSID'] has the proper ID though, it doesn't make any sense to me.
This is how I set the session variables.
$_SESSION['userID'] = $userInfo['ID'];
$_SESSION['userType'] = $userInfo['userType'];
$_SESSION['programID'] = $userInfo['programID'];
This is the jQuery
$("#content").load("viewUsers.php");
All pages have session_start() at the very top. The session variables also didn't work when I tried window.open and window.location instead of a jQuery load() function.
Some how the session variables are getting lost even though I have the correct session id. If anyone could shed any light on this I would really appreciate it!
As of right now I'm populating hidden fields and using a post function instead of load to get around it. I understand this isn't the best way, but it's the only way I could figure out how to do it.
Edit:
Here is the top of the index which read the session variables fine.
<?php
session_start();
//require("session.php");
if(!isset($_SESSION['userID'])){
header("location: ../login/index.php");
}
?>
Here is the entire viewusers
<?php
session_start();
//foreach($_POST as $name => $value){
//$_SESSION[$name] = $value;
//}
//echo " session id " . $_COOKIE['PHPSESSID'];
var_dump($_COOKIE);
var_dump($_SESSION);
?>
<?php require("adminFunctions.php"); ?>
<h2>View Current Users</h2>
<?php require("userlinks.php"); ?>
<table id="userTable" class="tablesorter">
<?php getUsers($_SESSION['programID'], $_SESSION['userType']) ?>
</table>
<script type="text/javascript">
$('td[name="userID"]').hide();
//$("#userTable th").click(function(){
//color();
//colorTable();
//color();
//});
function colorTable(){
$("tr:odd").css("background-color", "#c0c0c0");
$("tr:even").css("background-color", "#ffffff");
}
function color(){
$("tr:odd").css("background-color", "#ffffff");
$("tr:even").css("background-color", "#ffffff");
}
$(document).ready(function(){
//colorTable();
$("#userTable").tablesorter({widgets: ['zebra']});
});
</script>
Another Edit:
Here is the javascript code to load viewusers
The only reason I'm using post is because I set the session variables as hidden fields in order to pass session variables. On viewusers I use a foreach loop to set the session variables. I understand this isn't secure.
function maintainUsers(){
$.post("viewUsers.php", $("#sessionform").serialize(),function(data){
//alert(data);
$("#content").load("viewUsers.php");
});
}
Might be a long shot but are you using any framework or cms? I know that wordpress would delete session variables (http://blog.ginchen.de/en/2008/08/15/session-variablen-in-wordpress/) can you show the javascript code you're using to load viewUsers? Are you programming on a local server?
If you got correct $_COOKIE['PHPSESSID'], then try to add session_id() assignment before session_start() like this:
<?php
/** Add this: **/
if (isset($_COOKIE['PHPSESSID']))
session_id($_COOKIE['PHPSESSID']);
/** Start session **/
session_start();
/** Rest of the script... **/
if(!isset($_SESSION['userID'])){
header("location: ../login/index.php");
}
?>
I use this all the time and have no problems with sessions in PHP.
You have some spaces before the php open tag. They send output to the browser, and thus, session doesn't get started.
I suspect that the session isn't being started. I've had similar problems in the past all to find out that the session was not started in the first place.
A question: did you try printing out the value in the session variable just to make sure it's there? :
Before calling the page
and after calling the page.
Normally, this sort of error occurs when you dont use session_start() to read the session data.
Try placing (Although, you said you have, I would suggest rechecking)
session_start();
At the beginning of your viewUsers.php
In case, the above is not the case, thenyour current page (the one from which you execute the .load() function) is resetting the session and tampering with the values. Unless you upload the code or find it out, there is no solution for this case.
I would suggest something simple.
Include this in EVERY file.
<?php
session_name("yourapplication_session");
session_start();
?>

Proper use of session_start() with session.cookie_domain

Try as I might, I cannot get my session values on the other side. My set up is:
At the top of page 1:
ini_set('session.cookie_domain','.domain.com');
session_start();
On the sub domain page:
session_start();
echo $_SESSION['myval']
;
What am I doing wrong here? All I get is an empty array.
session_start needs to be called on every page that uses session variables. not just the first one

Categories