I have 1 SESSION variable that will load when a login form is inserted and it passes the test. But, the variable will only work in one page and when I click on a different page that includes the same file which gives me the SESSION, it doesn't work. It will only work for pages that are linked to the form. I am using the post method. sample.php <- site that is in action="sample.php" therefore its linked.
Beginning code for sample.php
<?php
session_start();
require 'php/login_admin.php';
if (isset($_SESSION['admin']))
echo ' all html code ';
Code for login_admin.php
if ($username == $row['username'] && $password == $row['password'])
{
session_set_cookie_params(3000, "/");
$_SESSION['admin'] = 'open';
} else {
session_close();
echo "Wrong password and username!";
}
NOTE I have this same set up for all pages and I do not know why only the pages linked directly to the form in the action attribute work.
On all your OTHER pages you only need to test for the admin session and if that fails then redirect to the login page... or display it... whatever you decide. But let's assume we go to a dedicated admin login page for fun...
So on All your other pages...except the login page...
<?php
session_start();
// Is the admin logged in?
if (!isset($_SESSION['admin']))
{
header("location:admin_login.php");
exit();
}
echo ' all html code ';
Related
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 created a login page to a php form that I also created. Whenever I fill the form with the required fields, I get redirected to a 'Thank you for your submission' page, that has the link 'Go Back to Form'.
The problem is, when I press the 'Go Back to Form' link, it assumes that I am not logged in anymore, and so I get directed to a white page instead.
Login Page Code:
<?php session_start(); ?>
<?php
if (isset($_POST['submitlogin'])) {
$username1= $_POST['username'];
$pass1= $_POST['password'];
if($username1==$nomepass && $pass1==$passpass) {
$_SESSION['CurrentUser']= $username1;
echo '**HTML FORM**';
}
else
{
//...
}
}
?>
Form 'Thank you' Page:
HTML code Inside PHP echo
...
echo ' <p> Back to login page </p>' ;
On the login form and subsequent pages using sessions, put an if statement to check if the session that tells that a person has logged in is set. Then, it will redirect you to a home page or whatever page you want if you are logged in.
That way, if you are not logged in, you can login otherwise, it will redirect you
<?php
session_start();
if(isset($_SESSION['CurrentUser'])){
// redirect to some page
}
else{
// do something else
}
You could also make that line to read as:
if(isset($_SESSION['CurrentUser']) && !empty($_SESSION['CurrentUser']))
Normally we can use the session and call it on every page where I wan to allow the register user, for example..
This is you php code
if (isset($_POST['submitlogin'])) {
$username1= $_POST['username'];
$pass1= $_POST['password'];
if($username1==$nomepass && $pass1==$passpass) {
$_SESSION['CurrentUser']= $username1;
header('location:index.php');
}
Now you can code in the index page like this...
<?php
if(!isset($_SESSION['currentUser']))
{
header('location:signin.php');
}
?>
if the session is set tyhen the above code will keep you login otherwise you will redirect to signin page..
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 currently have a login form that redirects the user to another page if the login is successful. The page is supposed to be a protected page that will not open for the user if they are not logged in and will redirect them to the login form page.
In order to do this I stored the login data (email & password) as session variables and used these to verify if the user is allowed to view the page.
In my login php page I have the following code
<?php
session_start();
if ($count == 1) {
$_SESSION['logged'] = 1;
$_SESSION['email'] = $myemail;
$_SESSION['password'] = $mypassword;
header("Location: account.html");
exit();
}
?>
And I begin my account html file with the following :
<?php
session_start();
if ($_SESSION['logged'] != 1) { //no session
header("Location:memberlogin.html");
exit();
}
?>
However any time I load the account page I am allowed to view it each time. Its my first time using the Session variableand Im not sure if i Used it correctly.
FIXED Thanks to suggestions below
I tweaked the code suggested below and my protected page is now working. Thanks for all the help.
The php code won't be referenced from an html page.
So, change account.html to account.php then add the session check code on top of the page as follows:
account.php:
<?php
if ($_SESSION ['logged'] !=1) {
//User is not logged in
header ("Location:memberlogin.html");
exit();
}
?>
However, redirecting is not the best solution, you can display an error message if user is not logged in, else grant user access to the page information.
You can implement it as follows:
account.php:
<?php
if ($_SESSION ['logged'] !=1) {
//User is not logged in, display an error message
echo 'You need to be logged in to access this page';
exit();
}
else{
//Display all information that only a logged in user can view
echo 'You are logged in, you can view the page';
}
?>
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.