UPDATED According to advice below. But still not working. Any help?
My company uses Active Directory LDAP and I'm using adLDAP to authenticate the user to login to this website.
So far, it works.. but every time they visit the page they must login again. The solution to this, I know is sessions. But I can't figure out what to store in the session in order to keep the user logged in.
This is included at the top of my login.php page:
auth.php
<?php
//include LDAP authenication script
require_once('LDAP/adLDAP.php');
$adldap = new adLDAP();
$username = $_POST['account'];
$password = $_POST['password'];
$authUser = $adldap->authenticate($username, $password);
$userinfo = $adldap->user_info($username, array("*"));
if ($authUser == true) {
$_SESSION['LDAP']['login'] = true
}
?>
Also at top of every page I have this:
<?php
if (empty('LDAP')) session_start();
if (!isset($_SESSION['LDAP']['login'] && $_SESSION['LDAP']['login'] !== true) {
header('Location: login.php');
exit; // dont forget the exit here...
}
?>
Right now, everytime I visit my index page index.php I log in, and I'm redirected to the main page. It works perfectly. But if I refresh the page, I'm asked to login again.
What do I store into a session so I don't have to log in everytime I refresh the page?
I know it starts with:
session_start();
But I don't know what to store in it?
You should only authenticate/include LDAP on your login page..
if success set a $_SESSION['LDAP']['login'] = true;
And check on every page with this.
if (!isset($_SESSION['LDAP']['login'] && $_SESSION['LDAP']['login'] !== true) {
header('Location: login.php');
exit; // dont forget the exit here...
}
Related
I tried to write my own authentication method (school project), and I'm stuck.
Please advise, how to solve a secure authentication:
There is an index.php which contains everything that needs to be "protected". I will copy the relevant parts of my code here.
updated index.php
session_start();
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['PHPSESSID'])){
if ($_SESSION['PHPSESSID'] == $_COOKIE['PHPSESSID']){
$authStatus = true;
}
}
return $authStatus;
}
if(!checkUserAuth()){
include_once(dirname(__DIR__).'/admin/authentication/login.php');
exit();
}
If the checkUserAuth() determines, that there is no properly authenticated user, will include the login.php and stop the rest of the script.
updated login.php:
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
$_SESSION['PHPSESSID'] = $_COOKIE['PHPSESSID'];
$_SESSION['login_user'] = $_POST['user'];
What I imagine that might happen, is that if the login details are correct, the login.php sets a cookie, and refreshes the page. Then the index.php will detect the cookie, and skip the login part.
The login is pretty much figured out, and thanks to Juned, I think it is working now. However I don't know how secure is this?
On a scale from 1 to very, how wrong I am?
There are loads of ways of doing this. The below pseudocode is not the most efficient but should work and I don't think what you've done above will actually work.
Does this help?
login.php pseudocode
<?php
session_start(); // this function checks if there's a session ID already set, if not, sets one.
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
// do your login details checking here
// if login details correct
// set a flag in the $_SESSION superglobal and whatever else you want to store about the user like their username e.g.
$_SESSION["loggedIn"] = true;
$_SESSION["username"] = "$_POST['user']"; // better practice to fetch a clean version from your database
//else return user to login page
}
?>
index.php pseudocode
<?php
session_start(); // this will fetch the session ID and other variables that you might have set e.g. username, logged in status
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true){
$authStatus = true;
}
return $authStatus;
}
if(!checkUserAuth()){
// redirect to login page. e.g.
header('Location: login.php');
exit;
}
?>
I'm pretty noob in PHP but I'm trying to exercise. Since yesterday I'm on a problem I can't even understand, I thought my code was correct but it seems wrong
So here is my function to allow pages for logged users only
functions.php
function logged_only()
{
if(session_status() == PHP_SESSION_NONE)
{
session_start();
}
if(!isset($_SESSION['auth']))
{
$_SESSION['flash']['danger'] = "You can't enter this page - not logged in";
header('Location: login/login.php');
exit();
}
}
So It's supposed to redirect me to login page if I'm not logged-in, simple
login.php
elseif(password_verify($_POST['password'], $user->password)){
$_SESSION['auth'] = $user;
$_SESSION['flash']['success'] = 'You're now connected';
header('Location: ../profile.php'); // user's homepage
exit();
There is some code above and under this, but it works pretty good.
So in this case the script should insert user's informations into his $_SESSION but it does nothing but redirect me at login.php. Also, the "profile.php" only contains "logged_only();" and a print_r (when I delete the redirection to login.php) of the $_SESSION, which shows nothing but "You can't access this page" (as I'm sending a message via $_SESSION)
Someone to guide me ? Thanks
You maybe should read about the session_start() in PHP: PHP Manual
In short words: session_start() starts a new session or recovers the already existing session with the client.
So after each redirect (also to your login.php) you need to call session_start().
There is no need for
if (session_status() == PHP_SESSION_NONE){
session_start();
}
You should only use
session_start();
(In both, your functions.php and your login.php) before accessing the $_SESSION variable.
functions.php
function logged_only(){
session_start();
if(!isset($_SESSION['auth'])){
$_SESSION['flash']['danger'] = "You can't enter this page - not logged in";
header('Location: login/login.php');
exit();
}
}
login.php
session_start();
// ... Rest of code
elseif(password_verify($_POST['password'], $user->password)){
$_SESSION['auth'] = $user;
$_SESSION['flash']['success'] = 'You're now connected';
header('Location: ../profile.php'); // user's homepage
exit();
I have been developing the following php script (+ sqlite database) to create a login for my web.
Up to now I had used just one PHP file, but now I want to use different files for login and protected contents, I mean, I used to have all my web in one file php (contents and password script were together) but now I want to detach it in different php files (one for the login, login.php, and other phps protected: index.php, calendar.php...)
I used this code to password-protect php content:
<?php require_once "Login.php"; ?>
but it doesn't seem to work: it displays the form to login next to the content I wanted to protect.
This is the php script I'm using as login.php:
<?php
$db = new PDO('sqlite:data.db');
session_start();
if (isset($_GET['logout'])) {
unset($_SESSION['pass']);
header('location: index.php');
exit();
}
if (isset($_SESSION['timeout'])) {
if ($_SESSION['timeout'] + 4 < time()) {
session_destroy();
}
}
if (!empty($_POST['pass'])) {
$result = $db->query("SELECT user,password FROM users");
foreach ($result as $row) {
if (password_verify($_POST['pass'], $row['password'])) {
echo "Welcome! You're logged in " . $row['user'] . "! <a href='index.php?logout=true'>logout</a>";
$_SESSION['pass'] = $_POST['pass'];
$_SESSION['timeout'] = time();
}
}
}
if (empty($_SESSION['pass'])) {
echo '<form method="POST" action=""><input type="password" name="pass"><form>';
}
?>
MY QUESTION IS: How can I use my php script to protect different files?Is there any way to embed a logout link too?
One way is to store a token in session variables when a user logs in. Confirm the token is there on each page, if it isn't redirect the user to the login page. For example assert_login.php:
<?php
session_start();
if('' == $_SESSION['token']) {
header("Location: login.php");
exit();
}
?>
Then, in the PHP at the top of each of your pages:
<?php
require('assert_login.php');
?>
You can also clear the session variable on logout, logout.php for example:
<?php
require('assert_login.php'); // has session_start() already
$_SESSION['token'] = ''; // empty the token
unset($_SESSION['token']); // belt and suspenders
header("Location: login.php");
exit();
?>
I was also going through same issue & the way I solved it:
PSEUDO CODE:
PHP SESSION START
if(isset(GET(logout){
SetLogout();
die()}
$redirect=false
if not session[auth] exists
if SERVER REQUEST METHOD IS POST
$redirect=true;
if POST(username) && POST(pass) exists
Sanitize both of them & assign to $user& $pass
if user == "John" && $pass == "secret"
Go To SetLogin();
else{
Go To SetLogout();
echo "Wrong Username or Password"
drawlogin();
die();}
} //user pass comparing ends
} //Server method is NOT POST, so maybe it is GET.
//Do nothing, let the control pass to next lines.
}//SESSION(auth) does not exists, so ask user to login
else {
drawlogin();
}
//Post-Redirect-Get
if ($redirect)
redirect header to this same page, with 301
die()
// Secret Content here.
function SetLogin($user){
$SESSION(auth) = TRUE;}
function SetLogout($user){
if SESSION(auth) exists
unset($SESSION(auth))
redirect back with 301, without query string //shake ?logout
}
function drawlogin(){
echo all the HTML for Login Form
What it does is, it checks various things/variables, and if all passes, the control passes to Secret Content.
Save it as pw.php, & include it on top of any file you want to protect. Logout can be triggered by Logout
Note that this is just a pseudo code, typed on a tablet. I will try to update it with actual version. It is not checked for errors. Use all standard PHP Security precautions..
I've been having a really rough time trying to implement a logon system for my web application.
I have the basic logic working as far as my index.php goes - if users try to navigate there and are not logged in it redirects them to the logon screen. Once they've provided correct credentials they are directed properly back to the protected index.php page.
This logic in code is seen here:
(index.php)
<?php
session_start();
include_once 'db_functions.php';
require_once 'access.php';
if (!userIsLoggedIn()) {
include 'login.php';
exit();
}
The problem occurs when a user attempts to navigate to another protected page. My logic was for protected pages to check whether the user was logged in, and if not send them back to the index which would in turn send them to a logon screen.
(protectedpage.php)
<?php
session_start();
require_once 'access.php';
echo "Logged in: " + $_SESSION['loggedIn'];
echo "User: " + $_SESSION['email'];
echo "Password: " + $_SESSION['password'];
// receive data from HTML readcalllog request
$rName=$_POST["registration"]; //irrelevant post data
$rowId=$_POST["rowid"]; //irrelevant post data
if ($_SESSION['loggedIn'] == FALSE) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
}
As you can see I included test echo statements to print out the details of the current session. When I would navigate to the page (turning off the redirect feature) to check the error messages it would print "000", without the "Logged in: " or "User: " text in front of it.
I performed a test and printed out the details successfully on the index.php page, so for some reason the session is being lost as I navigate from index.php to another protected page.
Any help would be greatly appreciated!
EDIT:
Here is a portion of the userIsLoggedIn() in access.php function which sets the session variables:
function userIsLoggedIn()
{
if (databaseContainsAuthor($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] =
'The specified email address or password was incorrect.';
return FALSE;
}
}
}
EDIT 2:
If I login to the index page, go to the protected page(which sends me to a logon screen) and login again, the sessions function properly and all protected pages are accessible.
I just need to figure out what's preventing the initial logon from creating a proper session that carries over.
First of all, you do not need to include session_start(); more then once in a page. Just insert it at the beginning of each file.
If I were you, I would use this statement to see if the user is logged in or not in the protected pages:
if ( !isset($_SESSION['email'] && !isset($_SESSION['password'] ) ) {
header('Location: http://www.myapp.com/index.php'); //if not logged in, return to index.php, which in turn redirects to a logon page.
exit();
} else {
echo "Logged in";
}
Also, I would recommend you using both $_SESSION and $_COOKIES to create a stronger log in system.
I'm trying to create a very simple login in php. All i want to do is,
register a session called user if the login is successful and direct the user to an inner page. in that inner page i have a include file which should check if the user session is created or not
if created -> authorize user
if not created -> redirect to login again.
But still I couldnt get this up and running. below is my code
login.php
session_start();
global $user;
if (($_POST['Submit'])){
$login = $_POST['login'];
$password = $_POST['password'];
if ((do_login($login, encrypt_password($password))) > 0){
$_SESSION['user'] = $login;
header('Location: home/dashboard.php');
}
else{
// load login again
}
}
and in my dashboard.php page this is how I'm checking it (and this part i have in another file called 'authentication.inc')
<?php
session_start(); // If
if (!isset($_SESSION['user'])) {
// User is not logged in, so send user away.
header("Location:/login");
die();
}
?>
updated ::
when I do an echo $_SESSION['user'], I'm expecting to see login name ($login) of the user which i done get :C
Am I missing something here... thanks in advance
cheers
sameera
if (!isset ($_POST['Submit']) || $_POST['Submit'] != 'Login'){
The code inside that if block won't get run if the form is submitted properly, because that condition reads " if Submit isn't set or it isn't 'Login' ". Try flipping the logic of that condition, ie:
if (isset ($_POST['Submit']) && $_POST['Submit'] == 'Login'){
-> " if Submit is set and it is 'Login' "
The Location header takes an absolute URL, not a relative URL, of the form:
header("Location: http://www.example.com/login.php");
There is an example on the PHP Manual header() page that can help to create the absolute URL.
And what #Brian says regarding the logic of your IF expression.