User authorization php/mysql with session [duplicate] - php

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();

Related

After payment success session destroying automatically

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

Destroying a session if it already exists?

What I am trying to do:
When a user hits the index.php page (the start of a couple pages of forms), I need any existing session to be destroyed and a new one to start. This is so that old session variables are not reused in the new process.
What I have done:
I believe this should check if a session already exists, if it does, destroy it and start a new one. (Need to use session_id() for the check)
if(session_id() == '') {
session_start();
}else{
session_destroy();
session_start();
}
The issue:
The previous session variables are still set and causing issues with the process.
Am I missing something in the way to reset all session varibles?
In documentation you can read:
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. session_destroy();
So you have to do following things:
$_SESSION = array(); //empty session variable
$cookieParams = session_get_cookie_params();
setcookie(
session_name(),
'',
0,
$cookieParams['path'],
$cookieParams['domain'],
$cookieParams['secure'],
$cookieParams['httponly']
);
session_destroy(); //and now you can call your function

why is php generating the same session ids everytime in test environment (WAMP)?

i've configured wamp in my system, and am doing the development cum testing in this local environment. i was working on the logout functionality, and happened to notice that the session ids being generated are same within the browser.
Eg - chrome always generates session id = abc, for all users even after logging out and logging in; IE always generates session id = xyz, for all users.
Is this an issue with wamp/ my test environment?
please find below my logout php script -
<?php
session_start();
$sessionid = session_id();
echo $sessionid;
session_unset();
session_destroy();
?>
You probably still have the cookie with the old session ID in it as neither session_unset nor session_destroy deletes that 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. setcookie() may be used for that.
So use setcookie to invalidate the session ID cookie after logout:
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
Another recommendation is to regenerate the session ID after successful authentication using session_regenerate_id(true).
Will work. Please try this
session_start();
session_regenerate_id(TRUE);
session_destroy();
You must regenerate the session id using function session_regenerate_id(). Without that, the session ID would be the same between page refreshes.
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.
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. setcookie() may be used for that.
Taken from http://php.net/manual/en/function.session-destroy.php
session_unset() and session_destroy() do not delete the session cookie. You have to manually unset it with a setcookie() call.
session_unset is the converse of session_register(), and session_destroy simply cleans out $_SESSION without affecting the cookie.
from the manual (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, or unset the session cookie.
To use the session variables again,
session_start() has to be called.
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.
setcookie() may be used for that.
Unless you specifically unset the cookie, then the cookie will still exist and the next time session_start() is called, it will use that as the session id. Closing the browser also should clear the cookie because they are generally set by php to expire on browser close.
To stop session hijacking follow the below code in PHP
session_start();
/* to stop session hijacking */
// Generate new session without destroying the old one
session_regenerate_id(false);
// Fetch current session ID and close both sessions to allow other scripts to use them
$newSession = session_id();
session_write_close();
// Assign session ID to the new one, and start it back up again
session_id($newSession);
session_start();

SESSION variables not passed from page after destroying the rest

I am at a total loss for words.
I allow an admin to reset their registration if reaching an error during the process. In theory, the following code should function like this:
page is reached, $adminvalidated is set based on session data. The $_SESSION array is cleared; the cookie is cleared on the consumer end; the session id is regnerated and the session is destroyed. Then the session is restarted and the previously mentioned variable is put back into Session.
the "echo" statements included below work but when I redirect to another page (commented out below), the session variables DO NOT carry over.
Yes I have started the session on the follow up page as well.
<?php
session_start();
ob_start();
if( $_SERVER['SERVER_PORT'] == 80) {
header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
die();
}
$adminvalidated = $_SESSION['ADMINVALIDATED'];
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_regenerate_id(true);
session_destroy();
session_start();
$_SESSION['ADMINVALIDATED'] = $adminvalidated;
echo $_SESSION['ADMINVALIDATED'];
/*
header("Location: ../a.php");
exit;*/
?>
In general it suffices to call session_regenerate_id(true) to change the session ID of the current session and invalidate the association with the previous session ID.
If you additionally want to clear any session data except $_SESSION['ADMINVALIDATED'], just do this:
session_regenerate_id(true);
$_SESSION = array(
'ADMINVALIDATED' => $_SESSION['ADMINVALIDATED']
);
From the manual page of session_start:
As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.
Just clear your session with session_unset, regenerate the session id and then reset your admin var. No need to destroy then restart the session.
I'm really not sure why you're going through all of these steps. session_regenerate_id() is enough on it's own to regenerate the session token and the associated cookie. The function creates a new session token and creates a new session cookie for you while preserving the values you have in the current session. Since setting a new cookie with the same name overwrites an old one isn't simply calling session_regenerate_id() enough?
Feel free to clarify things if I've missed something.

Truly destroying a PHP Session?

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();

Categories