I have this php code
if (isset($_SESSION['error']))
{
echo "<span id='error'><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
What Does $_SESSION['error'] means
and unset one please explain
$_SESSION contains all session variables (user ID of logged in user for example). You can set a session variable like this:
$_SESSION['foo'] = 'bar';
And access it later (after multiple page loads still, that's why it's so useful) using:
$foo = $_SESSION['foo'];
echo $foo; //Displays 'bar'
Your code checks if there is a session variable set, and if so display an error and unset the session variable. So I would guess this is to show a one-time error when something went wrong. Using a session variable means you can execute this code on a different page then where the error happened.
$_SESSION['error'] means a an array key of $_SESSION which was generated by you.
It looks in the session, which is a temporary storage that is unique to the user and more often than not is mean to last for the time a user stays on a page in a single "visit session", for a variable (actually rather an array key) called error; it then injects whatever that contains (likely an error message) into a piece of HTML, and after that, it deletes the error from the session storage with unset().
Take a look on the documentation for $_SESSION.
Related
I was trying to pass an error message to another page using session variable. On the handler page, the session was initialized in the manner:
function sess() {
$index = $_POST['name'];
$_SESSION['error'] = ($index == '') ? 'name cannot be empty' : $index . " is a good name";
header("Location: http://website-name.com/form");
}; sess();
and on the other page is something like:
if(isset($_SESSION['error'])) {
echo $_SESSION['error']; unset($_SESSION['error']);
};
Now if the form is submitted with an empty field, the error name cannot be empty becomes the value of the session. After that, if the name is then set, the value of the session doesn't change but still returns name cannot be empty.
I've checked to see if it has something to do with the fact that the session was called within a function. got no idea! but found online a way to unset all variable using session_unset. But it's actually one session variable that i want to unset and i found something like session_unset($_SESSION['error']). However, using it did not unset all session but the $_SESSION['error'] doesn't get set anymore within the function unless i use the unset($_SESSION['error']) which doesn't terminate the first session that is set.
So what is actually going wrong? how does unset_session() works differently form unset()? what does it has to do with being inside a function? As far as i can recall, $_SESSION[] is a global variable just like $GLOBALS[] which can be access in any scope.
I've created a login which sets a session variable to the users id which I get from my database. After the user clicks login after entering their details I redirect them to the home page which uses the session variable to get the users id for display purposes. The problem I am having is with the session variable. This is what my code looks like (simplified):
$_SESSION['user_id'] = $User_id;
header('Location: http://localhost/Projects/Login/home.php');
exit();
This is the snippet of code which sets my session variable, I have tested an it works. The next snippet of code is the function which is called from the home page (home.php). It is used to check if the user is logged in or not
function logged_in(){
return isset($_SESSION['user_id']);
}
I then use this if statement to perform different displays based on whether the user is logged in or not, again it has been simplified.
if( logged_in() === true ){
$session_user_id = $_SESSION['user'];
print "logged in";
}
else{
print "not logged in";
}
The problem seems to be with the if statement as it unsets the session variable to an empty array. If I print out the session variable I get Array(). I have started a session on each of the pages.
There seem to be two issues here.
First is the array keys; you're using user in one case and user_id in the other.
The second is speculative; you said it results in an empty array (I assume you have var_dump($_SESSION) or similar to confirm this?). If so it suggests you haven't started the session. You need to call session_start(); to get access to the session data.
Each time your script runs it needs to get access to the sessions stored on the server, this is why you run session_start(). The long version is that it obtains a lock on the local file which stores the session data (leading to whats known as session locking). As a result you may (for longer running scripts and/or performance) wish to call session_write_close() when you're finished with the $_SESSION superglobal.
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.
Question related to PHP memory-handling from someone not yet very experienced in PHP:
If I set a PHP session variable of a particular name, and then set a session variable of the exact same name elsewhere (during the same session), is the original variable over-written, or does junk accumulate in the session?
In other words, should I be destroying a previous session variable before creating a new one of the same name?
Thank you.
$_SESSION works just like any other array, so if you use the same key each time, the value is overwritten.
Tom,
It depends on how you use the session variable, but it generally means "erasing" that variable (replacing the old value by the new value, to be exact).
A session variable can store a string, a number or even an object.
<?php
# file1.php
session_start();
$_SESSION['favcolor'] = 'green';
$_SESSION['favfood'] = array('sushi', 'sashimi');
?>
After this, the $_SESSION['favcolor'] variable and the $_SESSION['favfood'] variable is stored on the server side (as a file by default). If the same user visit another page, the page can get the data out from, or write to the same storage, thus giving the user an illusion that the server "remembers" him/her.
<?php
# file2.php
session_start();
echo $_SESSION['favcolor'], '<br />';
foreach ($_SESSION['favfood'] as $value) {
echo $value, '<br />';
}
?>
Of course, you may modify the $_SESSION variable in the way you want: you may unset() any variable, append the array in the example by $_SESSION['favfood'][] = 'hamburger'; and so on. It will all be stored to the session file (a file by default, but could be a database). But please beware that the $_SESSION variable acts magically only after a call to session_start(). That means in general, if you use sessions, you have to call session_start() at the beginning of every page of your site. Otherwise, $_SESSION is just a normal variable and no magic happens :-).
Please see the PHP reference here for more information.
Yo. I'm trying to make a simple login system in PHP and my problem is this: I don't really understand sessions.
Now, when I log a user in, I run session_register("user"); but I don't really understand what I'm up to. Does that session variable contain any identifiable information, so that I for example can get it out via $_SESSION["user"] or will I have to store the username in a separate variable? Thanks.
Let me bring you up to speed.
Call the function session_start(); in the beginning of your script (so it's executed every page call).
This makes sessions active/work for that page automagicly.
From that point on you can simply use the $_SESSION array to set values.
e.g.
$_SESSION['hello'] = 'world';
The next time the page loads (other request), this wil work/happen:
echo $_SESSION['hello']; //Echo's 'world'
To simply destroy one variable, unset that one:
unset($_SESSION['hello']);
To destroy the whole session (and alle the variables in it):
session_destroy();
This is all there is about the sessions basics.
The session is able to store any information you might find useful, so putting information in is up to you.
To try some things out, try the following and see for yourself:
<?php
session_start();
if(isset($_SESSION['foo']))
{
echo 'I found something in the session: ' . $_SESSION['foo'];
}
else
{
echo 'I found nothing, but I will store it now.';
$_SESSION['foo'] = 'This was a triumph.';
}
?>
Calling this site the first time should store the information, storing it the second time will print it out.
So yeah, you can basically put anything you like in the session, for instance a username.
Keep in mind, however, that the session dies as soon as the user closes his browser.
$_SESSION['user'] must be set to your user's name/id so that when you try to read it the next time, you'd be able to identify that user. For example:
login:
$_SESSION['user'] = some_user_id;
user area:
$user = $_SESSION['user'];
// extract the user from database, based on the $user variable
// do something