I am doing a small project in that i have user data in session. In the middle the user will do payment, after payment success, the session is destroying automatically.
Now am not able to get user data from session. (How can i achieve this with out using COOKIES).
Note: I have tried using:
header('Access-Control-Allow-Origin: *');
But no use.
Hello this is an example from PHP manual i hope it might help. Firstly start your session by session_start(); and once all your transactions are completed destroy is by session_destroy();
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
$_SESSION is a special array used to store information across the page requests a user makes during his visit to your website or web application.
While there may be many users accessing the site at the same time, each with his own session, it’s thanks to unique IDs assigned and managed by PHP for each session that allows each user’s session to be available only to himself. Session information is stored on the server rather than the user’s computer (as cookie data is stored), which makes sessions more secure than traditional cookies for passing information between page requests.
Using Sessions
Before you can to store information in a session, you have to start PHP’s session handling. This is done at the beginning of your PHP code, and must be done before any text, HTML, or JavaScript is sent to the browser. To start the session, you call the session_start() function in your first file:
<?php
// start the session
session_start();
// store session data
$_SESSION["username"] = "Qateel";
session_start() starts the session between the user and the server, and allows values stored in $_SESSION to be accessible in other scripts later on.
In your second file, you call session_start() again which this time continues the session, and you can then retrieve values from $_SESSION.
<?php
// continue the session
session_start();
// retrieve session data
echo "Username = " . $_SESSION["username"];
Ending a Session
As important as it is to begin a session, so it is to end one. Even though a session is only a temporary way to store data, it is very important to clean up after yourself to ensure maximum security when dealing with potentially sensitive information. It is also good practice and will avoid having a huge amount of stale session data sitting on the server.
To delete a single session value, you use the unset() function:
<?php
session_start();
// delete the username value
unset($_SESSION["username"]);
To unset all of the session’s values, you can use the session_unset() function:
<?php
session_start();
// delete all session values
session_unset();
Both examples only affect data stored in the session, not the session itself. You can still store other values to $_SESSION after calling them if you so choose. If you wish to completely stop using the session, for example a user logs out, you use the session_destroy() function.
<?php
session_start();
// terminate the session
session_destroy();
Few Tips
Despite there simplicity, there are still ways using sessions can go wrong.
Timing-out sessions is a very important action if you are dealing with users logged in to your website or application.
if (isset($_SESSION["timeout"])) {
// calculate the session's "time to live"
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
header("Location: /logout.php");
}
}
Use a database to store data at the earliest moment you know the data will be persistent; don’t let it stay as part of the session for too long as this opens it up to possible attack.
Use session_destory() once you don’t need to use the session any more.
You may want to go through:
php sessions at #SO
php sessions security at #SO
Related
I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
To destroy a session you should take the following steps:
delete the session data
invalidate the session ID
To do this, I’d use this:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
The PHP Manual addresses this question.
You need to kill the session and also remove the session cookie (if you are using cookies).
See this page (especially the first example):
http://us2.php.net/manual/en/function.session-destroy.php
In the one site I've made where I did use PHP sessions, I never actually destroy the session.
The problem is that you pretty much have to call session_start() to check for your $_SESSION variables, at which point, lo and behold, you've created another session anyway.
Hence on my site I just made sure that every page called session_start(), and then just unset() those parts of the session state that matter when the user logs off.
$_SESSION = [];
#unset($_COOKIE[session_name()]);
session_destroy();
This is my code to control authentication on a website. I'm not sure if my logic is correct. If the username and password are correct the following happen:
if(session_start())
{
session_regenerate_id(true);//without this the session ID will always be the same
$_SESSION['loggedInUser'] = $uName;
echo 'You are now logged in';
}
else echo 'Right password/username but session failed to start';
Subsequent pages check to see if the user is logged in by
session_start();
if(isset($_SESSION['loggedInUser'])
{
//rest of page
}
else echo 'you must log in';
When logging out I have
session_start();//if I don't have this the next line produces an error
session_unset();//destroys session variables
session_destroy();//ends session
I red not to call session_start() on logout but if I don't have it there I get the message Trying to destroy uninitialized session. How can I fix this?
Is it recommend or not to create a finger print based on the IP address and user agent? I red it's bad because multiple computers can share the same IP address if they are in, for example a computer lab, and all the traffic goes through a proxy and the same computer could change it's IP address if it's dynamic. On the other hand, how often does this happen? It may be worth the few blocked valid uses to prevent all session hijacking.
Even if you could recommend reputable articles I should read to learn about this topic that would be great, thanks.
5/6 answers have votes less than 0 :( Could down voters comment so I know what to look out for?
First of all you should read the Mozilla WebAppSec Security Coding Guideline - Session Management and OWASP A3-Broken Authentication and Session Management. You can configure PHP's session handler to meet these requirements.
The first flaw you should prevent is A9-Insufficient Transport Layer Protection. In short you do not want someone to hijack a session using a tool like Firesheep. This attack can be prevented by forcing the browser to only send the session id over https:
session.cookie_secure=1
You can prevent an attacker from obtaining the session id using XSS by setting the httponly flag:
session.cookie_httponly=1
You always want to use a cookie to store your session id. If the session id can be passed using a GET or POST variable then an attacker could use Session Fixation attack to hijack a session. Another way of thinking about this attack is that you don't want an attacker to create a session for another user:
session.use_cookies=1
session.use_only_cookies=1
Next you want to make sure you have atleast 128 bits of entropy from a CSPRNG. Under *nix systems you can use /dev/urandom:
session.entropy_file="/dev/urandom"
session.entropy_length=16
The session handler isn't everything. You still need to worry about Cross-Site Request Forgery attacks (aka CSRF or "Session Riding"), and Cross-Site Scripting (XSS). XSS can be used to defeat CSRF protection (even with http_only cookies!). Clickjacking can also be used by an attacker to perform unauthorized actions.
After you set these configuration options, just call session_start(). As for destroying the session call session_destroy() when the user logs out, its that simple!
To securely destroy a session I would use the following code:
session_start();
// Unset all session values
$_SESSION = array();
// get session parameters
$params = session_get_cookie_params();
// Delete the actual cookie.
setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
// Destroy session
session_destroy();
In order to destroy a session you need to start it first, as you have found out it doesn't work if you don't include session_start();
The session_regenerate_id(); Function generates a new session id for the user. If used with true (session_regenerate_id(true);) then the old session id is deleted from the server when it generates a new one. The reason behind generating a new session id on every page is that it makes session hijacking much harder (Nearly Impossible?) to perform because of the users constantly changing session id.
(View PHP.net manual on session_regenerate_id();)
When authenticating a user you should always check something like the IP address or Browser, these are constant things sent in the request to the server that do not change in the life time of your session, and if they do then you know something dodgy it happening. I always create two session variable one that stores the user ID so I can query a database for data, and another that stores the users password, IP address and Browser String all in one hash (sha512).
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
// Query Database and get hashed password
$login_check = hash('sha512', $password.$ip_address.$user_browser);
if($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
The password is secure even though it is being stored in the session. This is because the password is hashed (Twice in this case) and because the session data is not stored on the users computer (Like cookies), it is stored in a session file.
I wrote an article on wikihow.com about secure login and authentication, is can be found here.
You can just write:
session_start(); // session should be started before it can be used.
You can assign userid of logged in member. For this you can take username and password from user input and check it in your db and return userid. For more security you can have strings for eg. "demo" and "test" just md5 both and mix it with userid in following manner.
$userid=md5("demo").$userid.md5("test");// you can set any string instead of demo and test.
$_SESSION['userid']=$userid;
While using it in other page,
session_start(); // If you are have not started it or included above code file in it.
As you know the strings while using just match it and find the exact userid from it and use it in your code.
For destroying it just use:
session_unset($_SESSION['userid']); // It will only unset the session userid completely.
Make sure that before use of any session you need to start it. In better way you can start the session in one file say init.php and include it every where where you want to use the session
You can first use session_id() to determine whether the user already got a session, if not, then use session_start().
example codes from Lithium framewrok:
/**
* Starts the session.
*
* #return boolean True if session successfully started (or has already been started),
* false otherwise.
*/
protected static function _start() {
if (session_id()) {
return true;
}
...
return session_start();
}
After call _start(), you can safely call session_destroy()
To destroy a session without using "start_session()", first verify whether there is an active session of not like below
$existingSessionId = session_id();
if ($existingSessionId != "")
{
// Initialize the session.
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
}
else
{
// No Active sessions
}
session_regenerate_id(true), just replace the old session id with the new one but it does not unset the old session id. This needs to be taken care by session_destroy and deleting session cookie.
Browser will send session cookie to server ever session is destroyed. PHP will get this session ID and when you do start_session(), it will use session id sent by browser. If you delete the session cookie, session_start will generate a new session id and you do not need to call session_regenerate_id()
When I log a user out of an app I am building I use session_destroy();
But when I go back to the page, all session variables are still set.
How can I completely destroy all session variables and ultimately require a user to log back in again?
Here is my code:
session_unset(); // clears all session variables
$_SESSION = array();
session_destroy(); // deletes session id
Thanks
After using session_destroy(), the session cookie is removed and the session is no longer stored on the server. The values in $_SESSION may still be available, but they will not be on the next page load.
If you need to clear the values of $_SESSION, set the array equal to an empty array:
Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.Still if you are concerned .
Try the following:
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
you are not calling session_destroy() for sure, your code may be unable to access it.
Post more code so we could help you
Some people say use unset($_SESSION["..."]) and some say session_unset() and some say $_SESSION = array() and some say session_destroy() and I am saying "for God's sake, this stuff is getting confusing, can someone please explain me which is the correct/secure way to log the user out" and what is used for what?
Appreciated...
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
RTM
Here is the difference between the entities
you can remove a single variable in the session
unset($_SESSION['shape']);
this would remove all the variables in the session, but not the session itself
session_unset();
this would destroy the session variables
session_destroy();
First of all, session_destroy() is not the same as the other methods. This one will destroy the current session data on the server, but will not unset any of the variables. It's simply the counterpart to session_start().
session_unset() is the deprecated equivalent to doing $_SESSION = array(). The latter and unset($_SESSION["..."]) are different only in the fact that the unset() route will only unset a single session variable, the one named in [...]. Never do unset($_SESSION), as that will interfere with the session mechanism itself.
Old question reference.
The only ones saying session_unset() are the ones stuck on obsolete versions of PHP - the function's been deprecated for a LONG time now.
The exact answer to this question depends on exactly what your code uses to determine if someone is "logged in" v.s. someone who is "logged out".
If you have a single $_SESSION['logged_in'] = true that your code looks for, then why unset it? Just set it to false and boom... user is logged out.
session_destroy — Destroys all data registered to a session
session_unset — Free all session variables
http://www.php.net/manual/en/book.session.php
The most I've seen used is to call them in this order.
session_unset();
session_destroy();
$_SESSION = array();
if you use session_destroy() then the cookie in the browser is also cleard (and probbley a new session gets created later)
personaly i use an object(s) to track different things (like public loggedIn = False; and a function witch actally logs the user in)
session_unset() is handy if you want to keep the coockie, but you will end up with more empty sessions in the server
I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
To destroy a session you should take the following steps:
delete the session data
invalidate the session ID
To do this, I’d use this:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
The PHP Manual addresses this question.
You need to kill the session and also remove the session cookie (if you are using cookies).
See this page (especially the first example):
http://us2.php.net/manual/en/function.session-destroy.php
In the one site I've made where I did use PHP sessions, I never actually destroy the session.
The problem is that you pretty much have to call session_start() to check for your $_SESSION variables, at which point, lo and behold, you've created another session anyway.
Hence on my site I just made sure that every page called session_start(), and then just unset() those parts of the session state that matter when the user logs off.
$_SESSION = [];
#unset($_COOKIE[session_name()]);
session_destroy();