To login I use:
<?php
session_start();
if($_POST){
$csUSER='USERNAME';
$csPASS='PASSWORD';
$user=$_POST['user'];
$pass=$_POST['pass'];
if ($user==$csUSER) {
if ($pass==$csPASS){
$_SESSION['cdb']="1";
header("Location: /");
exit;
} else {
$passerror='<span class="errormsg">Wrong Password.</span>';
} // END IF PASSWORD
} else {
$usererror='<span class="errormsg">Wrong Username.</span>';
} // END IF USERNAME
} // END IF $_POST
?>
To allow myself to do admin tasks per page (included in all pages [top of page]):
<?php
session_start();
if(isset($_SESSION['cdb'])){
$loggedn="WORD";
}
?>
This allows me to:
<?php
if ($loggedn=="WORD") { WHATEVER }
?>
And to make sure I only have access to backend pages when logged in (included in all backend pages):
<?php
// backend login check
if($loggedn!="WORD") {
header("Location: /"); // if not logged in, go to homepage
exit;
}
?>
The problem is, it works perfect on my pc, but I have another pc my wife uses for data collation and it does not stay logged in on her pc. We both use Linux (Fedora) with FF. I have been over ever line of code in each page, help!
A few things to check:
Ensure that you are starting with a clean slate. Clear cache and cookies in your browser to ensure that you don't have an old session open.
Ensure that session data is being stored on the new machine. Session data is commonly stored in /tmp
Ensure that there is no client-specific code being executed in relation to the session.
Call the exit function after redirecting to another page, otherwise the following code will be executed anyway, what can lead to strange behaviour.
if($loggedn != "WORD")
{
// redirect to login page
header("Location: login.php");
exit;
}
// the following code will be executed if exit is not called
...
Related
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".
I am working with php session as one of my experiment. Trying to learn by developing a script. But I have stacked. I am not quire sure why the php session isn't working.My log in page redirecting my page when i submitting correct email address and password. I am trying to skip log in page if session is set. But its not redirecting. here is the code. Even there has no error log output. So i became so confused what wrong with my code. I am looking for expert suggestion on my experiment.
<?php
session_start();
#Working With Session
if (isset($_SESSION['UserId'])) {
# code...
header('location:/management/index.php');
exit();
}
require_once("../configuration.php");
#Veriable collected From Login Panel
$Submitted_Email_Address=$_POST['email'];
$Submitted_Password=$_POST['password'];
$encrypt_Submitted_Password=md5($Submitted_Password);
#Lets gather Data From MySql Database
$con=new mysqli($hostname,$dbusername,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
die('The connection to the database could not be established.');
}
$query="SELECT * FROM users WHERE Email_Address='$Submitted_Email_Address'";
$result=$con->query($query);
$row=$result->fetch_array();
$SQL_Password = $row['Password'];
#LookUp Mysql Database to Get username/user id to store in session
$SQL_UserID=$row['id'];
$SQL_UserName=$row['username'];
$SQL_FirstName=$row['First_Name'];
$SQL_LastName=$row['Last_Name'];
$SQL_Role=$row['Role'];
if ($encrypt_Submitted_Password!=$SQL_Password) {
echo "Please check your email address and password again";
}
elseif ($encrypt_Submitted_Password == $SQL_Password) {
$_SESSION['UserID']=$GLOBAL['SQL_UserID'];
$_SESSION['UserName']=$GLOBAL['SQL_UserName'];
$_SESSION['FirstName']=$GLOBAL['SQL_FirstName'];
$_SESSION['LastName']=$GLOBAL['SQL_LastName'];
$_SESSION['Role']=$GLOBAL['SQL_Role'];
header('location:/management/index.php');
}
#Lets CLose All The MySql Connection
$result->free();
$con->close();
?>
After that i tried to see if the session is not set then redirect the page. but its not redirecting. I tried the following code to check if the session is not set let redirect the page. but not redirecting
session_start();
#Working With Session
if (!isset($_SESSION['UserId'])) {
# code...
header('location:/management/index.php');
exit();
}
You need to change your header call:
header('Location: /management/index.php'); // notice capitalization and spacing; they matter.
I guess you are missing something so silly. your code seems that its a php file which gather email address and password from a login page and validate it and then redirect it two another page.
I think your login page (might be login.html, access.html) is not redirecting. So your should put this following php code block in the login page. not here in the login.php which is only used to validate the inputed data. Happy coding and keep your mind calm. :)
and you have to use 'UserID' not 'UserId'
session_start();
#Working With Session
if (isset($_SESSION['UserID'])) {
# code...
header('location:/management/index.php');
exit();
}
Remove "!" from isset or put redirect in else clause:
eg:
session_start();
#Working With Session
if (**!**isset($_SESSION['UserId'])) {
# code...
header('location:/management/index.php');
exit();
}
www.example.com/index.html on my website is a page that asks for a password, and when entered, runs through www.example.com/login.php.
<?php
if (isset($_POST['pw']) && ($_POST['pw'] == "mypassword"))
{
// Location after Logged in
header('Location: http://example.com/kareha/index.html');
}
else
{
// If not Logged in
header('Location: http://example.com/index.html');
}
?>
And then gets redirected to www.example.com/kareha/.
The problem is, anyone can just type in and directly navigate to www.example.com/kareha/.
Is there any way I can protect this index file (or anywhere else on the site) so anyone who isn't logged in is redirected to the main login page?
Also, would it help if it was protected through .htaccess? (/kareha/index.html is automatically updated according to a template, which has broken every time I mess around with it)
Edit: Maybe something along the lines of starting a session with /login.php and then having .htaccess in the /kareha/ folder check for the session?
you need to use sessions or .htpasswd. To use sessions, change your html files to php
here's the top of your login script
<?php
session_start();
// see if the form has been posted
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// check for the password
if($_POST['pw'] == "mypassword") {
// set a session
$_SESSION['loggedin'] = true;
// redirect to kareha/
header('Location: http://example.com/kareha/index.php');
}
} else {
header('Location: http://example.com/index.html');
}
// put HTML and login form here...
the very top of kareha/index.php
<?php
session_start();
if(!isset($_SESSION['loggedin'])) {
// redirect to login page
header('Location: http://example.com/index.html');
}
// put rest of page here
you can read about sessions here: http://www.php.net/manual/en/book.session.php
Edit: I misread the original question. Revised...
Really annoying problem I can't solve/can only partially solve. Nice juicy one for you pros.
I've got a basic login system set up. Like this:
Login.php:
line 1: session_start();
Check if($_SESSION['logged_in'] == true) header("Location: /controls.php);, incase they've already entered their details.
If they haven't entered them yet, user enters credentials, if valid: $_SESSION['logged_in'] = true;
After database credentials are checked and session is set to true, redirect using PHP header("Location: /controls.php);
Bear in mind, the session is now set.
Controls.php
line 1: session_start();
line 2: if($_SESSION['logged_in'] != true) {header("Location: /index.php");}
Instantly I get taken to index.php ONLY IN CHROME AND FIREFOX.
Also, I have accounttools.php, where the session is again required. Once I try to access accounttools.php, the session is destroyed/unset and any attempt to load accounttools.php results in the header redirect to my /index.php page, again ONLY IN FIREFOX AND CHROME.
I've also got to add in something. If I go back to login.php and re-login, everything works fine and the session gets set properly. Is this a browser-based bug? PHP is executed before any data gets sent to the browser, so how on earth can these browsers act differently if the PHP has already been executed by the time anything reaches the user?
Login file:
// Login.php
<?php session_start();
if($_SESSION['logged_in'] == true)
{
header("Location: /controls.php");
exit();
}
if($_POST['username_login'] && $_POST['password_login'])
{
// Do necessary database work to check credentials (edited out here).
// ...
// Check re-hashed pass against database hash (password checking)
if($make_password == $current_user[0]['password'])
{
// If this is OK login is a success.
$_SESSION['logged_in'] = true;
header("Location: /controls.php");
exit();
}
}
?>
Controls file:
// controls.php
// This page instantly redirects to index.php
<?php session_start();
// Go to homepage if logging out.
if($_POST['logging_out'])
{
unset($_SESSION['logged_in']);
header("Location: /index.php");
exit();
}
// No access unless logged in.
// This session seems to no longer exist at this point. Why??
if($_SESSION['logged_in'] != true)
{
header("Location: /index.php");
exit();
}
?>
Edit: I've discovered something else: If I login and manually enter the URL of the $_SESSION-restricted page, the $_SESSION is not destroyed.
There is some part of the header() redirect that is causing th $_SESSION to become unset/destroyed in Google and Mozilla.
I've also been Googling like crazy and apparently this is a common problem amongs PHP coders. Someone must have a clue what this is?
I see a problem with the way you are redirecting after a successful login: It is a javascript redirect so it will only happen after all the php has finished executing and the result has been sent to the browser. That means that codes after your redirect are executed as well.
I would recommend not outputting anything to the browser until the very end and use the:
header("Location: /...");
exit();
combination everywhere where you want to redirect so that you are sure that nothing happens to your session after the redirect code.
To avoid getting headers already sent problems, I would also recommend getting rid of stuff like:
?>
<?php
like on the first lines of login.php.
Again, extremely noob PHP question.
I have a very simple login page
<?php
session_start();
if (isset($_SESSION['username']))
{
header('Location: main.php');
exit();
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
if (try_login($user,$pass))
{
$_SESSION['username'] = $user;
header('Location: main.php');
exit();
}
}
?>
<html> <!-- and login form below... >
And also a very simple main page:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('Location: .');
exit();
}
?>
<html> <!-- etc, etc -->
I expect the following things to happen:
If I navigate to http://localhost/main.php before logging in, I should be redirected to http://localhost/.
If I navigate to http://localhost/ and log in successfully, I should be redirected to http://localhost/.
Unfortunately, #2 doesn't happen. What could be wrong with my code?
You should use fully qualified url:
header('Location: http://localhost/main.php ');
You may be running into a race condition here. I've run into it several times...you set some stuff in the session, but the next page doesn't see it. This is usually caused by the browser requesting the second page so quickly that the first hasn't had time to write the session -- so the second doesn't see the changes to the session variables.
Try calling session_write_close() before you send your redirect header.
You must use absolute URIs like Location: / or Location: /main.php.
<?php
session_start();
if (isset($_SESSION['username']))
{
header('Location: main.php');
exit();
}
How is the person supposed to log in? You redirect if the $_SESSION doesn't have the username set BEFORE you do any code that would actually set that variable. That makes the login code effectively unreachable.