I am trying to pass a session name to a page, via url, and retrieve it using $_GET, to then set the session name, then I can start the correct session.
However I get errors, and a blank sessionName..
Example:
$sessionName = $_GET['sessionName'];
session_name($sessionName);
session_start($sessionName);
Any idea why this doesnt work? If I take out session_start and echo sessionName, it functions ok and echoes the session name.
Works fine with me:
$_GET['sessionName'] = 'MYSESSION';
$sessionName = $_GET['sessionName'];
session_name($sessionName);
session_start($sessionName);
echo 'Session name: '.session_name().'<br>Session id: '.session_id();
output:
Session name: MYSESSION
Session id: rtf3pjftivccsbbduplqcgk1j0
Related
Hey guys I'm trying to pass a php variable to another page. I tried it with sessions but no result.
newspaper.php
$newspaper= $newspaper['newspath'];
print_r($newspaper);
this outputs:
path/to/the/newspaper.
Now I want to use the variable in the second page.
newspaperviewer.php
echo $newspaper;
$SESSION = $newspaper;
I tried the first one but no result. The second one seems to be faulty.
Hope you guys can help me out.
Session is what you are looking for. A session variable can store a value and use this value on all pages of your project.
First thing to do is to start session on each file on your project. You can do this like this example
<?php
session_start(); //declare you are starting a session
$_SESSION['newspaper'] = "New York Times"; //Assign a value to the newspaper session
?>
On the other file you can use the value of the session by trying something like this
<?php
session_start(); //always start session don't forget!!
echo $_SESSION['newspaper'];
// This will echo New York Times
?>
Store the variable after starting session on page A, like so:
// FIRST PAGE (foo.php)
session_start();
$_SESSION['name'] = 'Jack';
Now, on the second page (or any page that you want to have access to $_SESSION, simply do the same but pull the variable.
// SECOND PAGE (bar.php)
session_start();
$name = $_SESSION['name'];
$_SESSION['name'] = null; // Or use session_unset() to delete all SESSION vars.
And that's how you pass variables using $_SESSION.
Please use this code to set session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
You can write like this
newspaper.php
session_start();
$newspaper= $newspaper['newspath'];
$_SESSION['newspaper'] = $newspaper;
Now you can use this session variable in
newspaperviewer.php
session_start();
$newspaper = $_SESSION['newspaper'];
echo $newspaper;
session_unset(); // remove all session variables
First
newspaper.php
$newspaper= $newspaper['newspath'];
//print_r($newspaper);
session_start(); //it starts your session here
$_SESSION['newspaper']=$newspaper; //it sets a session variable named as newspaper
Second
$newspaper= isset($_SESSION['newspaper'])?$_SESSION['newspaper']:''; //checks and sets value
echo $newspaper; //outputs value
For more see session_start
http://php.net/manual/en/session.examples.basic.php
First you will need to start the session by using session_start() at the top of your page. Second, a session variable is written like this: $_SESSION['foo'].
I suggest you read these pages to get a better understanding of what's going on.
http://php.net/manual/en/reserved.variables.session.php
http://www.w3schools.com/php/php_sessions.asp
I have following problem, I am trying to set cookies without any success. setcookie(); function returns true so it looks like it setting cookie however when I am trying to access it on the same or following page I get error 'Undefined Index....'
<?
session_start();
ob_start();
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',NULL);
//added to see if Cookie is set
echo "<br/>";
var_dump($_COOKIE);
exit();
if($_GET['paypal'] == 1){
header("Location: /paypal-express-checkout/process.php");
}else{
header("Location: /insert_order.php");
}
ob_end_flush();
exit();
?>
next page follows like this
<?php
session_start();
include_once("../includes/inc_config.php");
include_once("../order.php");
include_once("config.php");
include_once("paypal.class.php");
#region POST
if(!isset($_GET['token'])) //Post Data received from product list page.
{
//Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
if(!isset($_COOKIE['order'])){
exit();
}
$paypal_data = '';
$ItemTotalPrice = 0;
$order = unserialize($_COOKIE['order']);
print_r($order);
exit;
You are setting the domain value to NULL. Try leaving the NULL away:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/');
OR set it to your domain:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',".yourdomain.com");
I would var_dump or print_r the $_COOKIE variable before I make a decision that it's not getting passed through. Holding that thought once you setcookie something gets registered into the $_COOKIE variable for sure.
I agree with the statements above since you only can access $_COOKIE on the next refresh but there is another way to do it to make your form or page more interactive.
I would register the cookie and use a php page refresh (display a working... div while thats happening) then come back to the page and try to do what you originally tried doing. Very basic but pretty much straight forward.
My php website flows like this:
Page1.php has an html form which POSTs to Page2.php
Page2.php stores all the POST data into SESSION variables and has a button leading to Page3.php
Page3.php has another form which POSTs its data to Page4.php
Page4.php then stores all its POST data into SESSION variables
My problem is that it may be nessicary for a user to click the back button on Page4.php to go back to Page3.php and change some input. AS im sure your all aware when they get back to Page3.php the form will be blank as the entire page is re-rendered in its default state.
To get around this and re-display the user's previous input im doing this:
<input value="<?php echo $_POST["guest1Ticket"];?> " type="text" name="guest1Ticket" id="guest1Ticket" onblur="isTicketNumber(this)" size ="22"/>
This being the important part - <?php echo $_POST["guest1Ticket"];?>
This works but creates another problem for me. If the user goes back to Page1.php (before colsing their browser) and starts the process over again when they get to Page3.php the data from their last run through will be loaded into the form.
What I figure I need to do is clear all of the sdession variables when the user visists Page1.php. I tried to to that like this:
<?php
session_start();
session_unset();
session_destroy();
?>
(The above is at the very top of my file with no whitespace before the first character.)
No Warnings are generated when Page1.php loads but the session variables are not getting unset. When I get to Page3.php the data from the last run is still being entered into the form.
How can I clear my session data correctly?
BTW I only need this to work in Chrome and thats where im testing.
Only use session_unset() for older deprecated code that does not use $_SESSION.
see session_destroy manual
example you can try and see how it works
session.php
<?php
session_start();
$_SESSION = array('session1'=>1,'session2'=>2);
echo $_SESSION['session1']; //1
$_SESSION['session1'] = 3;
echo "<pre>";
print_r($_SESSION); //session one now updated to 3
echo "</pre>";
$_SESSION = array();
if ($_SESSION['session1']) {
echo $_SESSION['session1']; // IS NOW EMPTY
} else {
echo "woops... nothing found";
}
?>
<p>
<a href="destroyed.php">NOW GOING TO DESTROYED PHP<a/>
</p>
<?php
session_destroy();
?>
destroyed.php
<?php
session_start(); // calling session start first on destroyed.php
print_r($_SESSION); // prints Array ( )
?>
From the documentation:
If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used,
use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);
And take care about session_destroy:
session_destroy destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session
Use session_unset(). Like this:
<?php session_start(); ?><!DOCTYPE html>
<html>
<body>
<?php
$_SESSION["variabletounset"] = "I am going to be unset soon along with all of the other session variables.";
print '<pre>' . "\n";
print_r($_SESSION);
print ' </pre>' . "\n";
session_unset();
print ' <pre>' . "\n";
print_r($_SESSION);
print ' </pre>' . "\n";
?>
</body>
</html>
This would output:
Array
(
variabletounset => I am going to be unset soon along with all of the other session variables.
)
Array
(
)
I am working on an online ticket booking systems where after making successful booking(after payment) I want to clear the session id. But the thing is I am not able to clear it although I have used session_destroy() to destroy the session.
NB: I have echoed the session_id to check if its reset or not.
URL: http://7sisters.in/7sislabs/
function book_final_tickets()
{
//var_dump($_SESSION);
$session_id = session_id();
$sql = "
UPDATE
tbl_seat_book
SET
final_book = 'Y'
WHERE
session_id = '$session_id'
";
//session_unset();
if($r = $this->db->executeQuery($sql)){
if(session_destroy()){
unset($session_id);
echo 'Booking successfull';
}
}
}
session_destroy() alone won't remove the client-side cookie, so the next time the user visits, they'll still have the same session id set (but their server-side session info will have been destroyed).
From the docs (emphasis mine):
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. ... In order to kill the
session altogether, like to log the user out, the session id must also
be unset. If a cookie is used to propagate the session id (default
behavior), then the session cookie must be deleted.
You can use session_regenerate_id(true) to generate a new session ID and delete the old one. Note that this will keep all of the information in $_SESSION as part of the new session ID, so you still need to use session_destroy if you want to clear the session info and start fresh.
e.g.
<?php
session_start();
$_SESSION['blah'] = true;
var_dump(session_id()); // q4ufhl29bg63jbhr8nsjp665b1
var_dump($_SESSION); // blah = true
session_unset();
session_destroy();
setcookie("PHPSESSID", "", 1); // See note below
session_start();
session_regenerate_id(true);
var_dump(session_id()); // gigtleqddo84l8cm15qe4il3q3
var_dump($_SESSION); // (empty)
?>
and the headers will show the session ID changing on the client-side:
Request Header
Cookie:PHPSESSID=q4ufhl29bg63jbhr8nsjp665b1
Response Header
Set-Cookie:PHPSESSID=deleted; expires=Mon, 27-Dec-2010 16:47:57 GMT
PHPSESSID=gigtleqddo84l8cm15qe4il3q3; path=/
(You can get away without the setcookie() call here, since you're creating a new session anyway, so the cookie will be overwritten by the new ID, but it's good practice to explicitly destroy the old cookie).
After destroying the session with session_destroy(), this worked for me:
setcookie('PHPSESSID',"",time()-3600,'/');
The key for me was setting the path to '/'. That was the only way to really destroy the cookie.
Call session_id before session_start, and set session_id manually .
Example 1: same session_id will be used
<?php
session_start();
echo session_id(); //4ef975b277b52
session_destroy();
session_start();
echo session_id(); //4ef975b277b52
?>
Example 2: set session_id manually (called before session_start())
<?php
session_id(uniqid());
session_start();
echo session_id(); //4ef975d3d52f5 (A)
session_destroy();
session_id(uniqid());
session_start();
echo session_id(); //4ef975d3b3399 (B)
?>
(A) != (B), so you can set session_id manually, see http://php.net/manual/en/function.session-id.php for more information.
Another solution, dont use session_id() , just create new session array:
<?php
$_SESSION['booked'] = false;
if($r = $this->db->executeQuery($sql))
{
$_SESSION['booked'] = true;
echo 'Booking successfull';
}
?>
Try this:
unset($session_id);
session_destroy();
Instead of
session_destroy();
I'd rather do only a
session_regenerate_id(true);
and you will get a new session_id
When a user logs in on our website, I want to change the session ID but keep whatever data is in the session. I want to do this for two reasons:
To prevent a user account to be used at multiple places simultaneously (because if two people are using the same account, the actions of one will undermine the actions of the other).
To let the user continue what he/she was doing on another computer (e.g moving from home computer to work).
These might seem contradictory, but really aren't if you think it through.
The problem is as follows; to get to the data that is currently in the session, I have to call session_start(). This means I cannot call session_id() afterwards to set a new session ID. Any ideas how to transfer the session data and change the session ID.
Update: I need to be able to choose the session ID myself. session_regenerate_id() therefore won't work.
You might be able to use session_regenerate_id():
<?php
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
?>
or even a cruder approach might work:
// save the session
session_start();
$session = array();
foreach ($_SESSION as $k => $v) {
$session[$k] = $v;
}
session_commit();
// create new session and copy variables
session_id("new session id");
session_start();
foreach ($session as $k => $v) {
$_SESSION[$k] = $v;
}
Use this. Put it to a function:
function update_session($newsessid = '') {
// Backup the current session
$session_backup = $_SESSION;
// Set current session to expire in 1 minute
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 60;
// Close the current session
session_write_close();
// Set a new session id and start the session
$newSession = session_id($newsessid);
session_start();
// Restore the previous session backup
$_SESSION = $session_backup;
// Clean up
unset($session_backup);
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
You would then call it when required:
update_session($customid);
Or, you may just be able to use something like this:
$path=session_save_path();
$whatever_session_id;
pass these variables to the next page:
session_id()=$whatever_session_id;
session_save_path()=$path;
You'd be setting the path of the new session id to the old session data....
I don't know if this is really what you'd want, be here it is.