php session creating / reading problem - php

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.

Related

PHP use SESSION in the multiple pages

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 ';

POST Data stored across we pages? [duplicate]

This question already has answers here:
Transfer variables between PHP pages
(5 answers)
Closed 5 years ago.
Sorry, this is a bit of a noob question, but...
I am creating a login page and I am having difficulty getting the login page to send me back to the web page that prompted the login redirect...
Can the previous page be stored via POST variable and accessed on the next page (login.php)?...I am having trouble just keeping that webpage url...if someone could show me how and explain why that would be amazing!
If I could just see how it looks to store variables to post so they can be viewed on the next page that would solve all my problems
original webpage:
<?php
//how do I post current url so it can be accessed on login
require_once('./../User_Auth/includes/authenticate.php');
?>
login webpage:
`header("Location:");`
Use Sessions to pass data to next page!
<?php session_start(); ?> // session starts with the help of this function
<?php
if(isset($_SESSION['use'])) // Checking whether the session is already there or not if
// true then header redirect it to the home page directly
{
header("Location:home.php");
}
if(isset($_POST['login'])) // it checks whether the user clicked login button or not
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "Ank" && $pass == "1234") // username is set to "Ank" and Password
{ // is 1234 by default
$_SESSION['use']=$user;
echo '<script type="text/javascript"> window.open("home.php","_self");</script>'; // On Successful Login redirects to home.php
}
else
{
echo "invalid UserName or Password";
}
}
?>
What I've understood from your question is that you are on page that a certain point will redirect you to the login page, and after the login you would come back to the previous page, right?
If so:
From the php $_SERVER var you can get this information.
Practice example:
file loginpage.php
<?php
//at the beginning you place the code that catch the POST data if a login request was sent
if(!empty($_POST["username"]) && !empty($_POST["password"])){
//HERE DO LOGIN TRY
if(LOGIN_SUCCESSFULL){
$page = $_SERVER["HTTP_REFERER"]; //this contain the previous page
header("Location: $page");
}
else{
// show an error
}
}
else{
//if you arrive at this point of the code, this means that the we are visiting login page, so we have to rendere the page
require_once 'login_page_body_with_login_form.php'
}
Of course there are more advanced and secure technique, but this should give both an answer and an idea of how make things together.
Use this code on the landing page to redirect to the login page, passing the landing page URL as a $_GET variable.
if ( USER_NEEDS_TO_LOGIN ) {
$login = "/path/to/login/page";
$login = $login . '?tgturl=' . $_SERVER[ "REQUEST_URI" ];
header("Location: $login");
}
You could pass your previous page value from current page to authenticate.php.
<?php
$previousPage = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
//how do I post current url so it can be accessed on login
require_once('./../User_Auth/includes/authenticate.php');
?>
You can then access $previousPage in authenticate.php.

PHP login script in a separated file

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..

keeping a LDAP user logged in with PHP session

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...
}

php session lost after submitting form

The code below page keeps session on GET requests or refreshing browser, but when I submit a form the session data is lost.
$user=$_POST['user']; $pass=$_POST['pass'];
if ($_POST['user'])
{ if($user==$un and $pass=$pw)
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?welcome'); }
else { $msg="chybny login"; }
}
if(isset($_GET['logout'])) { session_destroy(); header('Location: '.$uri); }
$cnt=$_SESSION['cnt']+1; $_SESSION['cnt']=$cnt;
Above is the code for login which re-directs me to the welcome page as it was verified, however the session is lost. If I just refresh or repeatedly load the page without submitting, the session holds by echoing the session variable cnt (counts up 1,2,3,...)
After submitting the form, I see session is lost and too cnt variable is reset?
I usually don't work with session directly try the following, place it a the top of your script :
session_start();
$uid = $_SESSION['uid'];
$cnt = $_SESSION['cnt'];
then work with the variable instead
The problem is likely your 'and' statement. It should be &&. The condition is not going to be true.
If you're 100% sure the code is all fine and the PHP.ini is the problem, based on your comments above. Look at this link at check the settings in the .ini http://php.net/manual/en/session.configuration.php
To pass the current session to the next page... I believe is what you are asking...
You are currently not passing the session to the next page and use session_start() at the top of the next page.
Change line 4 to:
{ $_SESSION['uid']=$Xid;header('Location: '.$uri.'?'.SID.'&page=welcome'); } // Where "page" is the name of the data you are retrieving
Or, you can save the session data to a cookie and then retrieve it on the next page.
You can alternately name the session when you use session_start("NameHere") on each page, however if the visitor has recently visited and the session not destroyed, they may see parse errors, if you have them enabled.
First of all, make sure that the the first thing you do on every page is to start a session (I recommend calling it once in a header file that you require on all of your sub sites).
So that you have session_start(); everywhere in the system.
Second of all, tighten up your code; make it easier to read. Something like
$userName = isset($_POST['userName']) ? $_POST['userName'] : false;
$password = isset($_POST['password']) ? $_POST['password'] : false;
$logout = isset($_POST['logout']) ? $_POST['logout'] : false;
$url = '../index.php';
if(!($logout))
{
if($userName && $password)
{
if($userName == $un && $password == $pw)
{
$_SESSION['loggedIn']=true;
$_SESSION['uid']=$Xid;
$_SESSION['message']="success";
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail, incorrect login information.";
}
}
else
{
$_SESSION['loggedIn']=false;
$_SESSION['message']="fail ; username and password not submitted.";
}
header("Location: $url");
}
else
{
session_start();
session_destroy();
session_start();
header("Location: $url");
}
And if you want to display unqiue content depending on whether a user is logged in or not, then you can simply check if the login session is set or not, on each page, instead of modifying the header for that.

Categories