I have written a simple code for $_SESSION variable in the first php file:
<?php
session_start();
$_SESSION["name"] = "John";
?>
and in another php file to render this:
<?php
session_start();
echo $_SESSION["name"];
?>
But after that i used session_unset(); and session_destroy(); and after that i can't render any new $_SESSION variable nor the existing one. I am using Microsoft WebMatrix program and Chrome as main browser. Any suggestions? Thank you in advance.
That is because session_destroy(); destroys the current session and also sends a header to the browser to delete the session variable. In the same time the session is deleted on the server (in PHP) and the $_SESSION variables can no longer be used. You can always try to save the $_SESSION in another variable;
session_start();
$_SESSION['test'] = 'foo';
Next page:
session_start();
$saveSession = $_SESSION;
session_destroy();
var_dump($_SESSION); //Gives an empty array
var_dump($saveSession); //Still has ['test' => 'foo']
More information: http://php.net/manual/en/function.session-destroy.php and http://php.net/manual/en/book.session.php
Also, sidenote, you do not need to open and close PHP tags if they are combined;
<?php
session_start();
echo $_SESSION["name"];
?>
works just as well as
<?php
session_start();
?>
<?php
echo $_SESSION["name"];
?>
Related
I have a profile page in my website that welcomes the user with his/her name using session variable. After I unset this variable, the page can still access that name. I cannot properly erase the data.
I've tried to set it to null, session_unset and session_destroy
<?php #session_start(); ob_start(); ?>
//Some HTML code here
<?php
if( isset($_SESSION["user"]) && $_SESSION["login"]) {
echo '<div><p>welcome ' .$_SESSION["user"]. '!</p></div>';
echo
"<form action='' method='post'>
<input type='submit' name='use_button' value='Log out' />
</form>";
if(isset($_POST['use_button'])) {
$_SESSION["login"] = false;
unset($_SESSION["user"]);
session_unset();
echo "logout successful.";
echo '<script>window.location.href = "same-page.php";</script>';
}
}
else
echo 'no login data.';
?>
//Some HTML code here
<?php ob_end_flush(); ?>
I expected that after the redirect, the first if condition would not be satisfied and it gives the output 'no login data' but it still can access the session variables.
External php file:
<?php
session_start();
$_SESSION["user"] = '' ;
$_SESSION["login"] = false ;
echo '<script>window.location.href = "../profile.php";</script>';
?>
I think you can do this by destroying the session by using session_destroy() Method.
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. To use the session variables again, session_start() has to be called.
You can more about it from session_destroy()
here you are doing session destroy but you also need to do unset that particular variable from sessions array just like below before destroying session.
unset($_SESSION['user']);
Put this line immediately after your redirect line
echo '<script>window.location.href = "same-page.php";</script>'; // redirect
exit; // close current php script after redirect
I know this question has many duplicates, but I tried several of them and none of those have been answered.
Here is my code for logout.php:
<?php
session_start();
require './codefiles/dbhelper.php';
$dbh = new DbHelper();
$dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\'');
session_unset();
session_abort();
session_destroy();
$_SESSION = array();
unset($_SESSION['username']);
unset($dbh);
header('location:index.php');
?>
But the session variables are just too "stubborn" to be removed. Neither session values are being cleared not the session variables are being removed. Object $dbh is being unset but not $_SESSION['username'];
Another unrelated problem, despite I am setting the LoggedIn = 0, in my SQL query, it just stays as 1 in database. LoggedIn field is of type 'bit'. SessionID field is set to blank though.
Any solutions please?
EDIT:
Removed echo $dbh->error as it was unnecessary.
EDIT 2:
Added session_destroy() as suggested by Hossam Magdy.
<?php
include 'codefiles/dbhelper.php';
if(!isset($_SESSION['id']))
{
header ("Location: login_form.php");
}
else
{
session_destroy();
die('You have been logged out.<meta http-equiv="refresh" content="0;url=login_form.php">');
}
?>
This is basically the "Logout" structure.
I don't know why, but the code for destroying the sessions was somehow not working in logout.php. It worked in index.php and other files, but will all sorts of unpredictable behavior.
Found a workaround to circumvent the problem. The logout.php has code as below:
<?php
session_start();
$_SESSION['logout'] = TRUE;
header('location:index.php');
?>
And add this code to index.php:
# Implement logout functionality
<?php
session_start();
if(isset($_SESSION['logout']) && $_SESSION['logout'] == TRUE){
foreach($_SESSION as $var => $value){
unset($_SESSION[$var]);
}
session_destroy();
session_unset();
}
?>
It may not be a standardized solution, but the code works for me every time, with no unpredictable behavior.
Thanks everyone for sharing their ideas.
Try this
<?php
session_start();
require './codefiles/dbhelper.php';
$dbh = new DbHelper();
$dbh->Execute('UPDATE surveyors SET LoggedIn=\'0\', SessionID=\'\' WHERE Username=\''.$_SESSION['username'].'\'');
echo session_status() . '<br />';
session_unset();
session_destroy();
echo session_status();
// header('location:index.php');
Let's see what session_status() says.
But on my projects unset && destroy work.
How to pass two value from one page to another in PHP using session.
$account=$_SESSION["account_no"];
$account1=$_SESSION["account_no"];
Session will be available through out the application (in all pages) until you destroy it.
To set a session,
<?php
session_start();
$_SESSION['variable_name_1'] = "value_1"; // or $_POST['accountno_1'];
$_SESSION['variable_name_2'] = "value_2"; // or $_POST['accountno_2'];
?>
In the other page, to get the values
<?php
session_start();
echo $_SESSION['variable_name_1'];
echo $_SESSION['variable_name_2'];
?>
FILE-1: WHERE YOU NEED TO SAVE THE ACCOUNT TO SESSION
<?php // NOTICE THAT THERE IS NO SPACE BEFORE <?php [THIS IS IMPORTANT!!!]
// FILE-NAME: file_1.php WHERE YOU HAVE TO SET THE SESSION VARIABLE
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
$_SESSION["account_no"] = $account;
FILE-2: WHERE YOU NEED TO GET THE ACCOUNT FROM SESSION
<?php // NOTICE THAT THERE IS NO SPACE BEFORE <?php [THIS IS IMPORTANT!!!]
// FILE-NAME: file_2.php WHERE YOU NEED TO READ THE SESSION VARIABLE
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// READ THE ACCOUNT NUMBER FROM SESSION DATA...
$account = $_SESSION["account_no"];
On the first page:
session_start();
$_SESSION['value1'] = 'First value';
$_SESSION['value2'] = 'Second value';
On the second page:
session_start();
$value1 = $_SESSION['value1'];
$value2 = $_SESSION['value2'];
File:1 where data will be store Session
<?php
session_start(); //before HTML tag
$_SESSION['one'] = $account_no1;
$_SESSION['two'] = $account_no2;
?>
File2: where you like to retrieve session
<?php
session_start();
echo $_SESSION['one'];
echo $_SESSION['two'];
?>
Sessions is a global variable in PHP.
Just create two session variables as use anywhere
<?php
session_start(); // should be at top of page or before any output to browser
$_SESSION['account'] = $account;
$_SESSION['account1'] = $account1;
Now access these session variables anywhere in any page but should start session before use, like:
<?php
session_start();
echo $_SESSION['account'];
I have a simple authentication: you login in the login.php page and you are redirected to the home.php page.
This is the code of login.php:
if(pg_num_rows($rs) == 0){ //I search in db for a row with username and password
$errMess = "error";
pg_close($conn);
}else{
$row = pg_fetch_row($rs);
session_start();
$_SESSION['username']=$_POST["nick"];
$_SESSION['admin'] = $row[0];
pg_close($conn);
header("Location: /home.php");
}
now in the home I have the header done in this way:
<?php require_once("scripts/functions.php");
require_once("scripts/config.php");
session_start();
?>
<div id="siteHeader" class="headersLeft"><?php echo WELCOME;?></div>
<div id="userContainer" class="headersRight">
Logged as: <?php echo getDisplayName(); ?>
<?php if(isset($_SESSION['username'])) {?>
<button class="button" onclick="location.href='/logout.php';">logout</button>
<?php }else{ ?>
<button class="button" onclick="location.href='/login.php';">login</button>
<?php }
?>
</div>
it doesn't work: even if data is correct it still gives me "guest", the session variable is lost in the header passage..how come?
Solved: i was under windows and the default path to the temp folder, where php actually saves session files, was wrong: was "/tmp" and was not recognized.
I set it to "C:\php\tmp" and it worked: session file was not saved at all!
Write session_start(); on top of everything (right after
<?php
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
or if still doesn't work then write your code like this:
<?php
ob_start();
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
Also don't forget to put these two lines at the top of your login.php page.
Hope it helps :)
I'm guessing there's some more code after the if statement that continues to manipulate $_SESSION. That's where $_SESSION['username'] is assigned the 'guest' value.
Remember, header("Location: /home.php"); only sets a response header. It doesn't redirect immediately, stopping script execution.
Place a exit; command right after header() to prevent execution from reaching the rest of the code:
header("Location: /home.php");
exit;
this works for me:
session_save_path ( "" ) ;
session_start();
I created two files
1.php
2.php
which are in the same folder(i am using xampp).
In 1.php used session_start() and also used $_session['name']=abc. Then i opened 2.php to check whether session was created or not
2.php:
<?php
if(isset($_session['name'])){
echo $_session['name'];
}
else{
echo "no session found!!";
}
?>
and it keeps on saying "no session found!!"
Plz help ...
I searched a few sites n they say that by default d session is for whole folder containing
d script and session_set_cookie_params($lifetime,'/') (where $lifetime=60*60) is also nt helping.
On d other hand if at d end of1.php i use require("2.php") then abc is displayed.
What you have done is right in 1.php,
however, 2.php must start the session before using it.
2.php
<?php
session_start();
if(isset($_SESSION['name'])) {
echo $_SESSION['name'];
}
else{
echo "no session found!!";
}
?>
You're missing session_start() at the top of your 2.php file which is needed to access $_SESSION variables.
<?php
session_start(); // missing
if(isset($_SESSION['name']))
{
echo $_SESSION['name'];
}
else
{
echo "no session found!!";
}
?>
You need to call session_start(); again at the top of every page where you want to access $_SESSION variables, not only on the page where you want to initiate the session.
<?php
session_start();
if(isset($_SESSION['name'])){
echo $_SESSION['name'];
}else{
echo "no session found!!";
}
?>