Please review this Stackoverflow post.
I have the same PHP problem as bob_cobb. Here's Brad Chrisite's answer:
Order of operations.
Place your session creation and
test-for-validity check at the very
top of the page so the rest of the
page can make judgment calls off the
existence of $_SESSION['username']
(Chances are you're trying to validate
them inside the content area so your
"yay" or "ney" message appears in the
desired section of the document.
Pretty, yes, but the whole top-half of
the page can't see that it's
[potentially] a valid session.)
He is basically saying that session_start() and the conditionals that check for session variables should be at the top, so that the rest of the page could act based upon that.
However, my session-check is at the top of the page.
<?php
session_start();
if ($_SESSION['username'])
//User is already logged in, echo the log out button.
...
else
//User is not logged in, echo the log in form & button.
...
//Login form validation if user is not logged in and submitted form.
//At the end, create session variable ($_SESSION['username'])
//Destroy session if user pressed log out button.
session_destroy();
?>
Everything works fine, but, as with the poster of the other question, I have to refresh my page, to get the top script executed (the script that checks for $_SESSION['username']).
Why is that?
Do not echo anything before your entire control flow is finished. What I mean by this is that you should work to separate logic from display (even better: use a pattern like Model-View-Controller). In your case, maybe you can do something like this:
<?php
/* Place all your control logic at the beginning.
Do not echo anything in this block. */
session_start();
if ($_SESSION['username']) {
$loggedin = true;
} else {
$loggedin = false;
...
//Login form validation if user is not logged in and submitted form.
//If login succeeded, set $loggedin to true.
//At the end, create session variable.
}
//Destroy session if user pressed log out button.
session_destroy();
/* Only display logic below, we do not change any state here */
if($loggedin) {
echo logout button
} else {
echo login form
}
?>
The answer is simple. You need not unset the session after making the user registration.
Try this
<?php
session_start();
if ($_SESSION['username'])
//User is already logged in, echo the log out button.
...
else
//User is not logged in, echo the log in form & button.
...
//Login form validation if user is not logged in and submitted form.
//At the end, create session variable.
//Destroy session if user pressed log out button.
//session_destroy();
--- do a redirect or a refresh here ....
?>
Related
So i created a navbar and add code similar to this, and here is what i have,
<ul>
some links
</ul>
<?php
if logedin == true) {
echo "you are loged in";
} else {
echo "please log in";
}
</nav>
now the other part of this code in another file called account.php,this isnt the real code i have but this is something im using to demonstrate,
$logedin = true;
but the code doesn't work and and the variable doesn't show on the fist page (the code on the top).
what can i do?
Thanks!
(EDIT) i forgot to say this, but the navbar is on more than 1 page and that the problem , and idk how to use post on more than 1 page.
A value that indicates whether someone is logged in or not would be best stored in the Session - then it will persist between requests to different scripts (by the same user), but not permanently.
e.g.
login.php
When the user has successfully logged in, set a variable
<?php
session_start(); //access the session
//...some code here to check username / password etc, and then if they are all ok, you can set them as logged in for the duration of the session....
$_SESSION["loggedin"] = true; //store a variable in the session
Then in home.php, when the user visits this page you can check the session to see if they logged in successfully or not:
<?php
session_start();
$loggedIn = $_SESSION["loggedin"];
//if not logged in, redirect back to the login page and end the script
if ($loggedIn == false) {
header("Location: login.php");
exit();
}
//otherwise, continue as normal...
There's a comprehensive explanation of how sessions work here.
I have multiple pages that needs to be protected depending on the user privilege. I have a php to check the current session variable upon page load.
page being tested; the php code is placed above the !DOCTYPE. this code is suppose to check for unlogged in customers. if not logged in or no session variable set redirect to error page otherwise do nothing and load page normally
<?php
if (!isset($_SESSION["username"])){
header("location: error.php");
}
?>
my session variables are only set after logging in, after logging in the user is redirected to the page referred to above:
if (mysqli_num_rows($results6) < 1) { //$results6 is a query to check if the user exits in the users database
$logInMsg = "invalid log in";
} else {
session_start();
$_SESSION["username"] = $uName; //$uName is a user input user name
header("location: pageabove.php");
}
the problem is that even after logging in I still get redirected to the error page
That would be because you haven't started the session yet. You need to specify a session start on each page that you intend to use sessions in (Read more about session_start()):
<?php
session_start(); // start session
// do check
if (!isset($_SESSION["username"])) {
header("location: error.php");
exit; // prevent further execution, should there be more code that follows
}
This is for everything. On your login page and all. Anywhere you want to harness the sessions, you need to start it, otherwise it's "lost in the wind".
This is my PHP code to end the session but when I click on the back button it still go back into my previous page.
<?php
session_start();
if(session_destroy()) // Destroying All Sessions
{
header("Location: login.php"); // Redirecting To Home Page
}
?>
Really you should not be able to view a page if you are not logged in. Just do this on the top of every page.
<?php
session_start();
//check some value that lets you know if a user is logged in.
if(empty($_SESSION['user_id'])){
header("Location: login.php")
}
the redirect will happen even if your site is cached.
take a look here: http://php.net/manual/en/function.session-destroy.php
This just deletes all data within session but not the session itself, You have also to delete the session id and the session cookie (setcookie())
I am new to PHP so have a very basic question
I creating a page I am creating a page initially with user id and password, once user id and password are entered and submit is clicked, AJAX is called to validate that against database.
once validation done I want to refresh the page which show more option to user
I was thinking to use session
but every time I refresh the page a new session is created
I put this at the top of the page as a test and always when F5 is press I see "new session" on top of the page
<?php
if (!isset($_SESSION)){
session_start();
echo("new session");
}
else
{
echo("old session");
}
?>
session_start must be called always before anything related to a session. After calling it, you can get or set values of the $_SESSION variable.
Reference.
Your code should be:
<?php
session_start(); // always call this at top
if (!isset($_SESSION['has_been_here'])){
$_SESSION['has_been_here'] = true;
echo("new session");
}
else
{
echo("already been here");
}
?>
From php.net:
session_start — Start new or resume existing session
That means you have to start your session with
session_start();
on every page, in the first line, which will start or resume it. Check the php.net manual, it will help you understand how to handle and check sessions correctly.
I created a login page in php named as index.php. Now when the user logs in it redirects to mypage.php. The login works fine. But also mypage.php gets open when I type the url of mypage.php even without login. I want the user must logged in to see mypage.php and incase if he changes the url in browser then an error message should be triggered. What to do?
1.localhost/index.php
2.localhost/mypage.php
In index.php, once the user gets logged in successfully, set an session. like $_SESSION['login'] = true; before redirect. If invalid login, use $_SESSION['login'] = false; Don't forget to start the session on the top of the page. session_start();
In mypage.php, check if that session is set or not. If not set, throw error, else show the page.
session_start();
if(isset($_SESSION['login']) && $_SESSION['login'] == true) {
echo 'You are welcome';
} else {
echo 'redirecting to login page';
header('Location: index.php');
exit;
}
How are you storing the state of being 'logged in'?
You'll need to have your mypage.php check a variable that has been set by the index.php's successful login process.
Can you paste your code here and I can take a look
In order for a login to work correctly, your "secure" page (I use that term relatively because nothing is truly secure) needs to have some sort of validation conditional. In other words you need to have some way of determining if the user is logged in.
A simple way to do this in PHP is to set a session variable when you process the user's credentials. For example:
When the user successfully logs in set a session variable like so:
$_SESSION['isLoggedIn'] = true;
Then on the mypage.php check to see if the variable is set:
if(!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] != true) {
header("Location: index.php");
exit;
}
Please also note, it is imperative if you are using sessions that you have session_start(); as the first line of all of your files. This allows $_SESSION variables that were set on a separate page to be able to be read on the current page.
Hope this helps.