I have a PHP program, called login.
When the user passes something, like email and password, login.php will return a session key to the user, if the login succeeds.
And I have JavaScript code to call this function to do the login.
How can I store this session key to identify whether the user is logged in?
The session is stored in a cookie by the server.
You don't need to do anything on the client.
a session is serverside.. not clientside.. so you cant set it through js
Sessions are declared manually like this:
$_SESSION['user'] = $_POST['username']; // or any other variable
You can then check on the other pages with PHP like this:
if(isset($_SESSION['user'])){
//do this if true
}
Related
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.
For a website, I need to route users to their own page. I have a login form, which sends data to a PHP file to check if the user's information is correct, and if so, forwarding the user to their page. The only problem is that I need to validate the user on arrival, to check if they logged in or just typed out the URL. I plan to use this with a POST, but how can I auto-send the constant (i.e. "logged-in")? Is there a way to do that through an HTML form (outputted from an echo) and sending it when the page loads? Thanks in advance!
EDIT 1: I understand that I must use Sessions, but whenever the page redirects it clears the session. The whole reason I was asking this was because I needed a way to keep the session active. How do I redirect in a way that doesn't clear the session?
In the PHP file that validates their credentials, start a "session". You can then apply session variables that can be called at any time while the session is valid. You can do this with POST, which is sounds like you're using, or by querying a database upon validation.
For example, upon validation:
session_start();
$_SESSION['username'] = $_POST['username'];
$security_check = mysql_query("SELECT * FROM userList WHERE username = '$username'");
$row = mysql_fetch_assoc($security_check);
$_SESSION['userId'] = $row['userId'];
$_SESSION['userFullName'] = $row['userFullName'];
On subsequent pages, you can put the following code at the top to check if the user logged in. If not, it will kick them back to the index page; otherwise the $_SESSION variables will be maintained.
<?php
session_start();
if (!isset($_SESSION['userId'])) {
echo "<script> window.location.replace('index.php?login=no') </script>";
}
?>
As suggested in the comments, I would recommend doing some further research on sessions to get a full understanding of how they work.
I am creating a log in script and I need to know where exactly should I put the session_regenerate_id() function when I want to log the user in. The way I do it is like this:
$user_id = $general->login($username, $password);
$_SESSION['user_id'] = $user_id;
The log in function basically returns the user's auto-incremental id in the table, and I store that in the $_SESSION variable as shown above. I have only showed the part of the logic where I use the Session variable because I just know where I should put session_regenerate_id to avoid session fixation attack. Before or after I assign the value?
Like so:
session_regenerate_id(true);
$_SESSION['user_id'] = $user_id;
Or after, like so:
$_SESSION['user_id'] = $user_id;
session_regenerate_id(true);
Thank you.
It does not matter, as long as you do it in the same request as storing users' id in the session (standard restrictions apply, eg. if you don't cache your output you are not allowed to print any characters before executing session_regenerate_id). Either way you call it, it will prevent others from using the old session id to access the session that has user_id stored.
From Session Management Basics:
session_regenerate_id() must be called prior to setting the
authentication information to $_SESSION.
So, you have to place it before $_SESSION.
Im trying to stop users of my spacebook page from navigating to other pages without having logged in first. I understand I am supposed to use session variables. I know I have the user remembered on a specific session by entering session_start(); at the top of the page. Would a new class file be necessary have the browser remember the client is logged in or not? Would the session need to be stored stored in the class object? If a user navigated to a page where access was authorised before they could get there where would I store the if/else statement needed in a seperate php file?
If a new class was necessary Im thinking it would look something like this:
class Loggedin {
private $isLoggedIn;
public function Loggedin($username) {
if (array_key_exists($username, $this->isLoggedIn) && ($this->isLoggedIn[$username] == $password))
{
return true;
}
else
{
return false;
}
}
}
After the User has been logged in you can simply store the User ID in the $_SESSION variable like this:
login.php:
if (login_correct($userid, $password)) {
// Login successful
$_SESSION['user_id'] = $userid;
}
An other PHP-file could look like this:
if (null !== $_SESSION['user_id']) {
// User ist logged in...
} else {
// User is not logged in!
}
Your logout.php can look like this:
$_SESSION['user_id] = null;
I think you are way over-thinking this.
Passwords never get stored for longer than they are needed (i.e. the initial authorization request, so your $password is not necessary, not that it's defined anyway).
You have access to $_SESSION everywhere. It's up to you if you want to wrap it in a class.
The authentication check is as simple as isset($_SESSION['username']) (assuming you set that session value on login.
The $_SESSION variable in PHP is something they called a superglobal. This means that this variable is accessible from any scope throughout your application. Simply use $_SESSION.
Same goes with $_GET, $_POST, $_REQUEST, $_SERVER and $_ENV. I'm sure I'm missing one somewhere :D
Remembering a user can be as simple as (after login success):
$_SESSION['userid'] = 1234;
Another page would query it like so:
if (isset($_SESSION['userid'])) {
// user is logged in
}
There's no need to store an object in the session to accomplish this.
How can I prevent a user from accessing a page when they are not logged in? I want him to be redirected to the login page. I know it has something to do with sessions.
It works like this:
Start a session: session_start()
If Session["user"] == null, redirect to the login page, else continue.
In the login page, ask the user for password using a form
Post this form to the login page
Check against your authentication service (e.g. a table in mysql) if the user is authorized
If yes, Session["user"] = $userName, redirect the user to the page. If no, prompt for password again
Of course, this is all very, very simple. In your session, you could keep a complex user object, or anything. Good luck coding.
As Svetlozar Angelov pointed out the following code would work well:
if (!isset($_SESSION['nID']))
header("Location: login.php");
However.. this would not actually secure the page against users who really wanted access. You need to make some adjustments:
if (!isset($_SESSION['nID']))
{
header("Location: login.php");
die();
}
This prevents bots and savy users who know how to ignore browser headers from getting into the page and causing problems. It also allows the page to stop executing the rest of the page and to save resources.
Its also noteworthy that $_SESSION['nID'] can be swapped out for any other variable you are using to store usernames or id's.
When he logs - store a session variable. Then in the beginning of every page
session_start();
if (!isset($_SESSION['nID']))
header("Location: login.php");
If the login is ok
session_start();
$_SESSION['nID'] = 1; //example
Follow these steps:
Create a login.php page accessible to everybody where a user enters her username and password in a form. This form must be submitted to login.php itself. (action='login.php'). Also include a hidden variable in your form which tracks if the form has been submitted.
If the hidden variable is set, check if the username ($_POST['user']) exists in your DB, and that the password matches the username. If it does, store the username in a $_SESSION variable like this:
$_SESSION['username'] = $_POST['user'];
If it does not, reload login.php like this:
echo 'header("login.php")'; //You should not have echoed anything before this
Now include login.php in every user page you create. Suppose you were writing an email application, create an inbox.php like this
include ("login.php")
Now, login.php will check if the session variable 'user' is set and allow access to authorised users only.