Why PHP session unset if more than one time refresh page - php

This is my code to check if user is logged in or not:
if (!$_SESSION['userInfo']['name'])
{
Redirect('login.php');
}
and code to redirect the page is:
function Redirect($url)
{
ob_start();
header('location:'.$url);
exit;
}
This code is working properly when i press the refresh button one time but when I press the refresh button more than one time then the session variable is unset and redirects to login page.
I am using this code with API that take almost 5-10 second to load the page.If i press refresh button before loading then it's happened.
What may be issue?

Try checking with empty()
if (empty($_SESSION['userInfo']['name']))
{
Redirect('login.php');
}
NOTE: Please make sure you are not setting any value in $_SESSION['userInfo']['name'] before login. Also after login you have to clear it.

Try using isset() function (ref: http://www.php.net/isset):
if (!isset($_SESSION['userInfo']['name']))
{
Redirect('login.php');
}
And be sure to not clear the $_SESSION variable during a valid session, and still, be sure to clear it when the user logs out.
Maybe still use:
if (!isset($_SESSION['userInfo']['name']))
{
header('Location: login.php');
}

You may be omitting the code from your snippet, but are sure you starting your session?
session_start()
if (!isset($_SESSION['userInfo']['name']))
{
Redirect('login.php');
}

Related

Need redirection to particular page after login

i have a secure login form and at the moment, i have set it to just redirect to a home page link, but i want to add some validation so that IF a user comes from a perticular page then they should be redirected to that page after logging in, but not sure how to do it, my current way is not working, here is what i have tried so far:
print $_SERVER['HTTP_REFERER'];
$previousPage = $_SERVER['HTTP_REFERER'];
if ($errors == "") {
if (do_login($form_email_address,$form_password)) {
// success!
if ($previousPage == "http://hiddensite/path/video/"){
redirect($previousPage);
}else{
redirect("/index.php?page=home&loggedin=1");
}
} else {
$errors = "Could not login. Please check your e-mail address and/or password and try again.";
}
and if your wondering what redirect() is, its just my function:
function redirect($url) {
// this function redirects from one page to another
ob_clean();
header("Location: $url");
exit();
}
Do you want to know if a user comes from another page on your own site? If so, you could add a session var to that previous page and test it on your login page.
On your previous page:
session_start();
$_SESSION['foo'] = "bar";
And on your login page -
if(isset($_SESSION['foo'])) {...}
Not a great way to keep track of referrers, but if you only want to check one page as per your question, this should work.
We seem to be missing some information in answering your question. The code you have provided seems fine but in order for us to pinpoint the issue we would have to see the do_login function as you previously posted in the comments (which is now retracted). Since you are always redirected to the home page that would mean that the do_login function always returns false or anything else but true.
Before you retracted the comment I did noticed you also used the sqlslashes() function a few times. Is this a function that you have created? Be sure to include this in your question.

Checking Session to direct to relevant page

I would like to know if anyone can help me with this $_SESSION variable problem. I want to add a script to a signup page that will allow someone that is already logged in to access the page from the backend and for someone who is not logged in to be redirected to the index page. Currently what is happening is that the page, when accessed from outside is redirected to index which is perfect, but from within the backend, when clicked on add user, it stays on the same page. Please excuse all the mistakes = still very new to PHP.
require 'function.php';
session_start();
if (isset($_SESSION['authenticated']) && !empty($_SESSION['authenticated'])) {
header('Location: ../../scripts/backend_login/signup.php');
} else {
header('Location: ../../scripts/backend_login/index.php');
}
You should start your session on every page where you use $_SESSION
session_start()
before the rest of your code
Start off by ensuring you have a session_start() on every page needing the session variable.
Next, change your code to this:
if (isset($_SESSION['authenticated']) {
if ($_SESSION['authenticated'] == true) {
header('Location: ../../backend_login/index.php');
} else {
header('Location: ../../backend_login/signup.php');
}
}
Try that and see
The true will only work if that is the value of the authenticated session
----EDIT----
The ($_SESSION['authenticated'] == true) is not vital, it is just another fail-safe to be double sure the correct session state is active, can be completed without this
I fixed my own problem. Here is the solution.
require_once('function.php');
session_start();
if (!is_user()) {
redirect('index.php');
}
thank you all for helping!

Any idea why I have to click the logout button twice to logout?

This is my code for logout.php
When I click LOGOUT on my webpage I'm building, I have to click it twice to logout, any idea why?
You seem to be using both a session and a cookie, probably for a 'remember me' functionality. However, the logout script only deletes one at a time.
Try to remove the else in the else if.
if (session exists)
{
destroy session
}
if (cookie exists)
{
delete cookie
}
First time you log out, the if is run through, destroying the session. Next time you log out, the else is run through, removing the cookies.
Look at PHP - session_destroy, there's an example on how to handle this.
You can also do this in one run, just do two independent ifs
if (isset($_SESSION['user_id']) {
...
}
if (isset($_COOKIE['user_id']) {
...
}

Ending A Session, Reset Variables Not Working?

I am writing a script which is supposed to end a session for a user, and log them out of the system, thus returning them to the login page.
My logout script looks like this:
<?php
$_SESSION['signin'] = null;
session_destroy();
header("Location: /test/index.php");
?>
Initially I reset the signin variable that way even if the session isn't destroyed the variable should have at least changed so that the system believes the user is logged out.
And at the top of my login page I have a condition to forward them to the home page if they are already logged in, that way that can't visit the log in page once already logged in. This portion looks like this:
<?php
session_start();
if($_SESSION['signin'] == 5)
{
header("Location: /test/home.php");
}
?>
So in short, when someone is logged in, and clicks the link to logout it utilizes the first code block to log out, and then is forwarded to the page containing the second blcok of code.
However, this page still forwards me back to the home page, believing the user is still signed in and thus I'm guessing the signin variable was not reset.
Thoughts on how to solve my issue?
session_destroy() does not unset any of the global variables within the session. Simply using:
session_unset();
to unset all global variables, or to only unset the specified variable, use:
unset($_SESSION['signin']);
You can try something like this.
session_unset()
you don't have to use
$_SESSION['signin'] = null;
using session_destroy(); should be enough
and I don't exactly know the deep stuff of PHP, but if you set a $_SESSION variable to NULL, PHP could read it as it is set to NULL which means 'it is set'? (don't know for sure though)
In this case, if you want to destroy a variable, you could do this:
Have a page named logout.php and whenever the user needs to logout, redirect him/her to that page. Now, inside that page you'll put the following, and here I'll explain you what this does:
<?php
session_start(); //Initializes the session
unset($_SESSION['thenameofyoursession']); //This unsets a specific session, so the user is logged out, in this case it would unset "thenameofyoursession".
$URL="/test/home.php"; //This is the redirect URL
header ("Location: $URL"); //This basically will send the user back to the redirect URL using header.
die(); //terminates the PHP script from running
?>
With that you should be fine.
Your procedure is fairly obvious and similar to one that we use, however, it would be best to unset() the entire session if nothing in it is valid. -- If they aren't logged in, no session variables should exist.
My logout.php script includes this:
session_start();
session_register("loginMessage");
session_unregister("authenticatedUser");
session_destroy();
// relocate back to login page
header("Location: /");
Which works. session_unset() is historically redundant.
Hope this helps.

Redirect not working with Header(Location ) and session variable

1: i use register.php to sign up the clients,
2: the data collected from the form is send to 1.php, it is saved in database
3: after form data is saved in database, 1.php forwards selected form data (myValue) to register.php?myValue='abc'
in 1.php, i am saving a session variable like this
#session_start();
$_SESSION['color']='blue';
the code of register.php is
if (isset($_SESSION['color'])) {
header('Location: http://mydomain.com/thankyou.php');
}
else {
#session_start();
some other stuff that was initially use for signing up the clients
my logic is to check for session variable and to redirect it to some-other page
when step 1 , step 2 and step 3 are complete, page should be
redirected to thankyou.php
currently, when step 1, step 2, step 3 are done, instead of opening thankyou.php, the following page is being opened
http://mydomain.com/register.php?myValue='abc'
however, if i re-open register.php or go back to step one (opening register.php), thankyou.php is displayed...
can somebody guide me where i am doing the blunder? why redirection is not being successful although session variables are being created?
code Update
i tried the following code at the top of my register.php
#session_start();
if (isset($_SESSION['color'])) {
header('Location:http://mydomain.com/thankyou.php');
exit;
}
else{
remaining stuff
it occasionally do the trick, redirects to the page, while on occasion (greater in number), it fails in redirecting to thankyou.php,, also the code needs to delete complete history and cache to work (after doing so, still miss hits occurs..)
Make sure you use exit(0); right after you do a header redirect otherwise php will still parse and run the rest of your script, sometimes it can cause some funny behaviour.
In your register.php, you can't test for the session variable before you issue the session_start, so your code should be more like:
session_start();
if (isset($_SESSION['color'])) {
header('Location: http://mydomain.com/thankyou.php');
}
else {
// Something else....
EDIT:
Another thing I've found useful when trying to set session variable in conjunction with redirects is to proceed to the redirect only after running a function. Here's how it would work:
$throwAwayVariable = setColor('blue');
if($throwAwayVariable ){ // separated out into a function so it wouldn't redirect before the session variable was saved
session_write_close();
header("Location: http://mydomain.com/thankyou.php");
}
function setColor($color){
#session_start();
$_SESSION['color']='blue';
return true;
}
Since not all your code is posted, you'll have to figure out where this goes, but I've always had my session vars work after this process.
Your session_start() call in register.php needs to be BEFORE you call any $_SESSION variables.
I have the same issue, then I try to add session_start and session_write_close, and it works!
session_start();
$_SESSION['status'] = 'Updated Poem successfully';
session_write_close();
header("location: index.php");

Categories