Session stops automatically - php

I have learned so much from stackoverflow. I have run into a problem that is strange,
Here it goes.
I have coding that checks if a session has started and if not, I start the session. No problem there
Here is my code
If (session-id = "")
{Session_start();
/* setting session ids */
}
I have an include file that submits a form to the same script (script above)
But when returning to the page via post method, the session gets started again, as if the session stopped.
Edit
If (session_id == "")
The mistake there was a typo.
The problem I originally had was that upon first initialization, I had set session arrays
/* If statement */
$_Session['test'] = ['1','2','3','4','5'];
/* end of if statement */
When user submits data to the same script, the session array will be null, giving an error. The way I solved it was to put session_start on the top of the script and no longer on the if statement. That seemed to solve the problem, thanks for all your input.

i think you want this
if(session_id() == '') {
Session_start();
/* setting session ids */
}
session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).
also you Call session_start() more than one there is no problem in that since
session_start() - Start new or resume existing session
in the php version >=5.4.0 you can also use session_status() it
session_status() is used to return the current session status.
Edited
Well it seems that Starting session twice is problem in some case
I am quoting this comment of DaveRandom
If The session is already started. You can't start it again. You can't resume something that isn't stopped. This will stop the message from appearing but I don't understand why you would want to call session_start() in the first place. Note also that session_write_close() doesn't destroy the local $_SESSION variable so make sure you don't try and write to it after you've closed the session.
so you can do this like
<?php
var_dump(isset($_SESSION));
session_start();
var_dump(isset($_SESSION));
session_write_close();
var_dump(isset($_SESSION));
session_start();
codepad

Check whether $_SESSION is set.
isset($_SESSION) or session_start();
http://codepad.viper-7.com/I3i9lv

You need to start the session at the top of every page, just to keep the session. That will not clear the running session, so you can just remove the condition for it to start.

Related

Why is ( $_SESSION = [];) making the server unable to handle the request?

I'm trying to clear the variables from a session and start a new one. From reading around about the variable issue, I think I discovered that this is the right answer:
( $_SESSION = [];)
But when I add that line to my code, on a line by itself within the PHP code, I get a message that "[the server] is currently unable to handle this request," indicating "HTTP ERROR 500."
Without that one command, the page works fine (except that the variables don't behave as I want them to). But every time I activate that line, I get the error. How can I clear the variables without making the server angry?
Update: I have also tried session_destroy(), but it has the same effect. Here is a little more context:
<?php
session_destroy();
session_set_cookie_params(3600,"/");
session_start();
?>
If I comment out the session_destroy() line, the page loads with no trouble. But with that line, I get the error.
Final update for others with this question: I've marked the correct answer. I needed to start the new session before unsetting the variables from the last one.
You should not use session_destroy() before session_start(). Try this:
session_start();
session_set_cookie_params(3600,"/");
session_destroy();
To remove all session variables use:
session_unset();
if you are having issues after destroying your session, then it is likely that your code is trying to access session variables that have not been set. I like to check with isset()
eg
$myVar = "";
if (isset($_SESSION('MyVar')) $MyVar = $_SESSION('MyVar');

don't I need to use session_start() to use session global variables?

A novice php learner. I read in a book, and continue to see this at certain forums and tutorials that the statement: session_start() is required to access all global session variables. And yet, multiple solutions offered at stackoverflow suggest using a block of this sort:
if(!(_isset($_SESSION['user']))){
session_start()
}
to be able to access the session variables. Based on my understanding, the session variable $_SESSION['user'] could only have been set at a previous php file by starting a session, and is "only" visible to the current page after the session_start() statement is called. Yet it produces the notice:
Notice: A session had already been started - ignoring session_start().
what am i missing?
Thanks everybody!
Your first block of code should be checking if the session variable is set, rather than the user variable exists in the session:
if(!isset($_SESSION)) {
session_start();
}
However, if you just ensure that you only have a single session_start() per page then you can avoid the "A session had already been started" notice.
session_start() is required to read / set any session variables.
Generally, I would think your code should look like this:
session_start()
if(!(_isset($_SESSION['user']))){
// do stuff here
}
However, the error message implies that you have already started the session elsewhere in your file.
You might have auto_start turned on somewhere (php.ini, .htaccess, etc)?
http://www.php.net/manual/en/session.configuration.php#ini.session.auto-start
Here is a scenario where your error would be triggered :
index.php:
<?php session_start();
require_once('some-page.php'); ?>
some-page.php:
<?php session_start(); // this would make an error when included to index.nl ?>
some-page.php should not have session-start in it as index.php already has started the session.
Also note that going to another page or even closing the tab will not reset your session variables ! so if you set S_SESSION['user'] = 'someuser'; , you close the tab and go to the website again, the session is still there and $_SESSION['user'] would still have someuser as value ! to manualy destroy the session , use session_destroy();

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.

How can you check if a PHP session exists?

Just wondering how to check if a PHP session exists... My understanding is that no matter what, if I am using sessions, I have to start my files with session_start() to even access the session, even if I know it already exists.
I've read to user session_id() to find out if a session exists, but since I have to use session_start() before calling session_id(), and session_start() will create a new ID if there isn't a session, how can I possible check if a session exists?
In PHP versions prior to 5.4, you can just the session_id() function:
$has_session = session_id() !== '';
In PHP version 5.4+, you can use session_status():
$has_session = session_status() == PHP_SESSION_ACTIVE;
isset($_SESSION)
That should be it. If you wanna check if a single session variable exists, use if(isset($_SESSION['variablename'])).
I find it best many times (depends on the nature of the application) to simply test to see if a session cookie is set in the client:
<?php
if (isset($_COOKIE["PHPSESSID"])) {
echo "active";
} else {
echo "don't see one";
}
?>
Of course, replace the default session name "PHPSESSID" with any custom one you are using.
In PHP there is something called the session name. The name is co-related to the cookie that will be being set if the session was already started.
So you can check the $_COOKIE array if there is a session cookie available. Cookies are normally the preferred form to interchange the session id for the session name with the browser.
If a cookie already exists this means that a PHP session was started earlier. If not, then session_start() will create a new session id and session.
A second way to check for that is to check the outgoing headers if the cookie for the session is set there. It will be set if it's a new session. Or if the session id changed.
isset($_SESSION) isn't sufficient because if a session has been created and destroyed (with session_destroy()) in the same execution, isset($_SESSION) will return true. And this situation may happen without your knowing about it when a 3rd party code is used. session_id() correctly returns an empty string, though, and can be called prior to session_start().
Check if session exists before calling session_start()
if(!isset($_SESSION))session_start();
You can call session_id before session_start. http://www.php.net/manual/en/function.session-id.php - read the id param
I've always simply used
if (#session_id() == "") #session_start();
Hasn't failed me yet.
Been quite a long time using this.
NOTE: # simply suppresses warnings.
Store the session_id in $_SESSION and check against it.
First time
session_start();
$_SESSION['id'] = session_id();
Starts a session and stores the randomly given session id.
Next time
session_start();
$valid_session = isset($_SESSION['id']) ? $_SESSION['id'] === session_id() : FALSE;
if (!$valid_session) {
header('Location: login.php');
exit();
}
Starts a session, checks if the current session id and the stored session id are identical (with the ternary ? as replacement for the non-existing short circuit AND in php). If not, asks for login again.
switch off the error reporting if noting is working in your php version put top on your php code
error_reporting(0);
I solved this three years ago, but I inadvertently erased the file from my computer.
it went like this. 3 pages that the user had to visit in the order I wanted.
1) top of each php page
enter code heresession start();enter code here
2) first page:
a) enter code here$_session["timepage1"] = a php date function; time() simple to use
b) enter code here$_session["timepage2"]= $_session["timepage1"];
b) enter code here$_session["timepage3"]=$_session["timepage1"];
3) second page:
a) enter code here$_session["timepage2"] = a php date function; time() simple to use
b) enter code here$_session["timepage3"]= $_session["timepage3"];
3) third page:
a) enter code here$_session["timepage3"] = a php date function; time() simple to use
the logic:
if timepage3 less than timepage3 on page 2
{the user has gone to page 3 before page 2 do something}
if timepage2 on page 2 less than timepage1
{the user may be trying to hack page two we want them on page 1 do something}
timepage1 should never equal timepage2 or timepage3 on any page except page1 because if it is not greater on pages two or three the user may be trying to hack "do something"
you can do complex things with simple arithmetic with the 3 timepage1-2-3 variables. you can either redirect or send a message to say please go to page 2. you can also tell if user skipped page 2. then send back to page 2 or page one, but best security feature is say nothing just redirect back to page1.
if you enter code hereecho time(); on every page, during testing, you will see the last 3 digits going up if you visit in the correct order.

PHP session_start() function: Why I need it everytime I use anything related to PHP sessions

For logging out a user from my website, I am redirecting the page to logout.php where I am using session_destroy() function. Even there also, logout functionality is not working without session_start() function. By adding session_start() function before session_destroy() function, I am able to logout the user successfully.
Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?
session_destroy() destroys the active session. If you do not initialized the session, there will be nothing to be destroyed.
Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?
So PHP knows which session to destroy. session_start() looks whether a session cookie or ID is present. Only with that information can you destroy it.
In the default configuration, PHP Sessions operate off of the hard disk. PHP asks you to explicitly tell it when you need this support to avoid unnecessary disk IO.
session_start() also tells PHP to find out if the user's session exists.
session_start() creates a session or
resumes the current one based on a
session identifier passed via a GET or
POST request, or passed via a cookie.
as per http://php.net/manual/en/function.session-start.php
Essentially by calling session_start(), PHP reads the header and cross references that session ID to what is on your system(file system/database/etc), which can then populate the $_SESSION that is relavent to that specific user. Which in turn allows you to call session_destroy() because it knows what session to actually destroy.
consider session_start() as your way of telling the php engine.... that you want to work with sessions.
and, as i understand it, always make that to be the first line ever in php page.
I was confused with the usage of session_start(); and every time I was using a session variable, I was calling session_start. Precisely, I had session_start(); more than once on each page (without even calling session_destroy()). For example,
// 1st call
session_start();
if (!isset($_SESSION['UserID']))
{
// Do something
}
else
{
// Do something else
}
// .... some other code
// 2nd call
session_start();
if (!isset($_SESSION['UserID']))
{
// Do something totally different
}
else
{
// Do something else totally different
}
This was creating a performance issue for me. So I ended up calling session_start(); just once at the very top of the page and everything seems to be working fine.
You have to call session_start once (and only once) in every file you want sessions to work in.
A common approach allowing you to only call it once is to have a dispatcher file as your index.php; call session_start in here and have this page include others based on the url's $_GET.
<?php
session_start();
if(isset($_GET['page']) && file_exists('pages/'.$_GET['page'].'.php') {
include $_GET['page'];
}
?>
//www.mysite.com/index.php?page=fish will display /pages/fish.php with session access

Categories