On my site, the login.php page (if successful login) will redirect to index.php and will start a session and 2 SESSION variables.
One of the variables started is a success message:
$_SESSION["message"] = "Login successful!";
the second is the user session variable:
$_SESSION["authenticatedUserEmail"] = $email;
the problem is that if I check the variables individually and then try and use them on the index.php page, only the first one that is checked will work.
This following snippet will show the $form_message but it will not show the $_SESSION["authenticatedUserEmail"]:
session_start();
if(isset($_SESSION["message"])) {
$form_message = $_SESSION["message"];
session_unset($_SESSION["message"]);
echo $form_message;
} else {
$form_message = "";
}
if (isset($_SESSION["authenticatedUserEmail"])) {
echo $_SESSION["authenticatedUserEmail"];
}
It does work when I only use one if(isset($_SESSION statement but I don't want to always include both inside the same statement.
I've done an error check:
ini_set('display_errors',1);
error_reporting(E_ALL);
but no errors appear.
Can anyone please suggest why this may not be working or if I am missing something?
Thanks in advance.
session_unset function free all session variable. this is why when you are using session_unset, next session variable is not founded. read the manual please.
http://php.net/manual/en/function.session-unset.php
to achieve what you want you can use unset function
unset($_SESSION["message"]);
hope this helps
Your call to session_unset is the problem, you should be simply using unset.
session_unset unsets the whole $_SESSION array.
Related
I am trying to verify that a user has logged in before showing them the page, using the method below, while the if/else method works when wrapped around plain html, it is failing when there is php involved. I am a novice by the way. What happens is the page simply loads as if the two tags below weren't there...which would be fine had I previously logged in, but I hadn't.
<?php
session_start();
if(isset($_SESSION['user'])) {
?>
HTML/PHP Page goes here.
<?php
} else {
header("Location: cms/admin/loginreadmode.php");
}
?>
Thanks in advance,
You can debug just below your session_start(); by printing your session:
echo '<pre>';
print_r($_SESSION);
die();
If $_SESSION['user'] isn't showing up in your array it isn't be set.
You can do this like this:
session_start();
$_SESSION['user'] = true;
Are you sure that you have add session support in every page?
if (!isset($_SESSION)) {
session_start();
}
This code should be working, so mistake is probably somwhere else I suggest checking if you set $_session["user] after login.
You should also replace your not-working code part with simple
echo "hello";
to chek it.
1) That is not a great method of checking whether a user is logged in, purely checking whether a user sessions exists can end up causing a lot of problems. Storing the ID in the sessions and then checking whether the ID is valid may be a better way,
2) When I copy the code above into a test document it goes straight to the redirect page in the else statement. This is down to the user session not being set, as soon as I set the user session before the code is executed it works fine. I see 'HTML/PHP Page goes here.'.
Setting the user session:
$_SESSION['user'] = 'TestUser';
You can change the code at the top of the page to be
<?php
session_start();
if(!isset($_SESSION['user'])) {
header("Location: cms/admin/loginreadmode.php");
die();
}
?>
Hello Friends I am new at forum
I have create a simple login page name as index.php with following code:
// I have already starts session by session_start()
$qry="select empCode from relaxo_employee_info where empCode='".$username."' and empPassword='".$password."' and empPost='Executive'";
$result=mysql_query($qry);
if($row=mysql_fetch_array($result))
{
$_SESSION['UID']=$username;
echo $_SESSION['UID']; //prints session data successfully so think session set correctly.
?>
<script>self.location.href='executive/order_place.php';</script>
<?php
}
then at starting of order_place.php I continue the session by session_start() and the following code in it to check valid session
<?php
session_start();
if(isset($_SESSION['UID'])==NULL) // at this point $_SESSION['UID'] find automatically empty. somehow Its blank completely.
{
?>
<script>self.location.href='index.php';</script> //because of session finds empty it redirects to index.php
<?php
}
?>
and strange things are happens I just share with u which helps you understand my problem
1) the same code is run on localhost successfully and does not work on my domain
2) sometimes session works successfully but sometimes not with same code without any changes
So guys please solve my problem and help me to come out from this issue
if(isset($_SESSION['UID'])==NULL)
is kind of a weird approach if you want to compare the $_SESSION variable with NULL. Instead, try
if(is_null($_SESSION['UID']))
and see if the problem still occurs.
Try like this...
<?php
session_start();
if(isset($_SESSION['UID'])) // check whether session is set or not.
{
if($_SESSION['UID'] == NULL) // check session is NULL
{
header('location:index.php'); // redirect to index.php page
}
}
?>
if(isset($_SESSION['UID'])==NULL) is where your problem is. If true == null or false == null it's never going to work.
isset($_SESSION['UID']) tests to see if your variable is set.
in order for you to test it's value try something:
if( isset($_SESSION['UID']) && trim($_SESSION['UID'])!='' )
{
// execute code here
}
I have a php page that should only be accessed by admin. I am using a php $_SESSION to validate the user. I have this code segment on top of my page which should only be accessed by the admin
if (!isset($_SESSION["uname"])) {
header("Location:../error.html");
exit;
}
if ($_SESSION["uname"] != "admin") {
header("Location:../error.html");
exit;
}
uname variable is getting pass to the page correctly, I am sure about that. But my validating process does not work as I expected. any user can access the page.
Is there anything wrong I have done here.
Did you output anything before doing these checks, even a single empty line is enough to prevent redirecting the page using
hearder()
As others stated I'd make sure you do
session_start();
But I have to assume you have the correct session values as you put
"uname variable is getting pass to the page correctly, I am sure about
that. But my validating process does not work as I expected. any user
can access the page. Is there anything wrong I have done here."
So that leads me to the header error, one way to tell is adding.
ini_set('display_errors', 1);
above your "validation checks" this should show any errors like "unable to send headers output already sent" etc.
Did you call session_start() function at beginning.
It would not work unless we call session_start before using any SESSION data.
http://www.php.net/manual/en/function.session-start.php
You probably forgot to call session_start() at the very beginning of the restricted page as well as the page where $_SESSION['uname'] is being set. Also make sure that $_SESSION['uname'] does not contains the value of 'admin' for other logged in users.
Note: You can debug values of super globals like $_SESSION using the print_r() or var_dump() functions.
See the example given below;
Start your session in your index or the desire page
sesstion_start();
Create this function to validate and redirect automatically
function isValidate($value, $autoRedirect = true){
if(empty($_SESSION['uname']) || $_SESSION['uname'] != $value){
if($autoRedirect){
header("Location:../error.html");
exit;
}else {
return false;
}
}
else {
return true;
}
}
Now simply call this method to validate the session by name. For example;
isValidate("admin");
isValidate("user");
BEFORE YOU MARK THIS AS DUPLICATE, I have read through all the answers on this topic and Non of them worked for me, this is why I am posting this.
So the problem is that the data for $_SESSION is not saving from page to page. Here is my test:
TestOne.php
<?php
session_start();
$_SESSION["user_id"] = 1;
if(isset($_SESSION["user_id"])) {
header("Location: TestTwo.php");
}
?>
TestTwo.php
<?php
if(isset($_SESSION["user_id"])) {
echo $_SESSION["user_id"];
}
?>
It goes to page two but it is a blank page. Why is the data not saving from page to page?
session_save in the php.ini is set to /tmp (I am using hostgator)
You are missing session_start(); on your TestTwo.php
FYI : You need to call session_start(); on all of your PHP files, if you are making use of Sessions.
I have read through all the answers on this topic and Non of them
worked for me, this is why I am posting this.
Really caught my attention btw.
for using session variables, u need to use session_start()
before that
session_start();
if(isset($_SESSION["user_id"])) {
echo $_SESSION["user_id"];
}
You need session_start() on every page that requires the session.
Is it possible to use a session variable, then unset it directly after?
Example:
//====
//Process Form
if ($_POST['Submit']) {
$update = $userSettings->update($_POST);
//If there are form errors
if (!$update) {
//Load the errors into an array
$errors = $update[1];
} else {
//Set the session
$_SESSION['showUpdated'] = true;
//Redirect to this page
header("Location: http://www.mysite.com/settings");
}
}
//==================
if ($_SESSION['showUpdated']) {
echo "Settings Updated";
unset($_SESSION['showUpdated'];
}
So after the form is submitted, if there are no errors:
Set a session to say the form submission was okay
Reload the page (to prevent re-submitted POST data)
If the 'showUpdated' session variable is set, display the "Updated" message
Unset the session variable (so we don't see the message on next reload)
Currently the problem is, if you unset the session variable straight after; It is as if you have un-set it before the "if exists" part.
Any solutions? Is this even the best way to do it?
Many thanks!
I noticed a small error in the original example that might cause other problems.
unset($_SESSION['showUpdated'];
needs to be
unset($_SESSION['showUpdated']);
Not including that end ) in the unset will cause an error.
That looks like it should work. Make sure you call session_start() before trying to use the session, and always exit() or die() after a redirect header.
I accomplish what you're doing a little differently. I keep a 'message' element in the session. I'll stick text in like 'Your data was saved', error messages, etc. Then, on each page (actually in a page template class), I check to see if the $_SESSION['message'] is set and not empty. If there's something there, I display the message and set the value to an empty string or null.
I do this from time to time. I never have any problems with it. But what I would add to yours is an exit() function call after the header redirect.
EDIT: The reason for the exit() is that it will prevent it from processing any further code and will eliminate the possibility of unset before you wanted to check after the redirect.
The header call without an exit after will continue running the page.
header("Location: http://www.mysite.com/settings");
exit;
Using that instead, should kill the page and not unset the session variable on the same page call.
Just check to see if it exists. This is safe to do before it has been defined and will tell you your answer after it has been defined.
if(!empty($_SESSION['showUpdated'])) {
Or you can just set it to false.
if ($_SESSION['showUpdated']) {
echo "Settings Updated";
$_SESSION['showUpdated'] = false;
}
And it looks like you use smaller version of PHP than 5.3, because in 5.3 you'll get notice when you use uninitialized value. So you should use isset function:
if (isset($_SESSION['showUpdated']) && $_SESSION['showUpdated']) {
echo "Settings Updated";
$_SESSION['showUpdated'] = false;
}