I am having an issue right now with sessions. I use a log in script to do initial authentication, and then i authenticate at the begining of each protected page, and finally i try to log out (code below).
The files exist on my server using PHP 5.6. I am using Win10 and Chrome on my pc.
SYMPTOMS:
Although session vars are destroyed, i can still use the 'back' button in my browser to view a page that does authentication. When i dump $_SESSION vars on that page (which i browsed back to using the back button of the browser) all $_SESSION var are non existent - but the page still loads.
COOKIES are still there. I have set cookie lifetime in my php ini to 1 (one second) for testing... they are still there after i supposedly delete them. Even when set to 0, they are still there after i restart the browser.
After reading symptom 1 above, i think many of you will guess, correctly, that the session is still alive and well - even after i close the browser, restart it and type the url of one of the protected pages directly in the address bar i am still able to view the page, even though the $_SESSION var that checks for authentication does not exist.
Would really appreciate advice.
LOG IN SCRIPT
//this page is called (using require_once) by the page
//that captures username and password
session_start();
//requirements
require_once "../php/path.php"; //sets the server search path
require_once "constants.php"; //does all the DEFINE stuff
require_once HTML_HEADER; //loads HTML code - doc type, head etc
require_once DATABASE; //does the dB connecting
//collect the POST
$uName = $_POST[uName];
$uPsswd = $_POST[uPsswd];
//build & execute sql query
**SQL to retreive uName and password here if match then...**
$_SESSION['approved'] = 'true';
require_once MAIN_CONTENTS; //main page after authentic log in
exit;
AUTHENTICATE CODE CALLED USING require_once BY EACH PROTECTED PAGE
if (session_status() == PHP_SESSION_NONE) {
session_start();
}//end if
//what's the time Mr Wolf?!!!
$now = time();
//although session exists, are we logged in and approved? If not kill session & eixt.
if (isset($_SESSION['approved']) && $_SESSION['approved'] != 'true'){
require_once "killSession.php";
require_once "notAuthorised.php";
exit;
}//end if
if (!isset($_SESSION['approved'])){
require_once "killSession.php";
require_once "notAuthorised.php";
exit;
}
//if session exists, how old is it? If older than 'discard_after' then kill session.
if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
require_once "killSession.php";
require_once "notAuthorised.php";
exit;
}//end if
else {
//logged in and approved so set timeout for 15 mins
$_SESSION['discard_after'] = $now + 30;
}//end else
THE killSession FILE
//check to make sure session exists - start if not
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['approved']='false';
}//end if
//following code caused 'headers already sent...'
//if (isset($_COOKIE[session_name()])) {
//$params = session_get_cookie_params();
//setcookie(session_name(),'',time() - 172800, '/', $params['domain'], $params['secure'], isset($params['httponly']));
//}
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
?>
Your issue is most probably caused by the POST data still being stored in your browser. By clicking the back button, your user is authenticated again and a session is created.
To resolve this issue you can use the POST-Redirect-GET method.
<?php
// Has the session been set?
if (!isset($_SESSION)) {
session_start();
}
// If a form is submitted, add the POSt data to a session
// and redirect
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['login_data'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
// Check if user wants to login, authenticate and unset login data
if (isset($_SESSION['login_data'])) {
// Authenticate
unset($_SESSION['login_data']);
}
?>
<form action="" method="POST" role="form" action="<?= $_SERVER['PHP_SELF']; ?>">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Username"
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
<button type="submit" class="btn btn-primary">Authenticate</button>
</form>
Related
I have two pages made in PHP, index (using it as login page) and main page (this one should be protected).
Index page has a login form that asks only for password (there are no users intended to be).
I want to make this:
1. When you enter password on index page, and if it's correct, the site will redirect you to the main page. If password is not correct then it will alert you about that.
2. Main page should not be visible if you have not entered password on the index page. If you have entered it then you will be able to see the main page.
I figured out that the easiest way would be to make it with PHP session check, but it's not working on my code, so can you please help me?
So this is my PHP code for the index page. Here the site needs to check is (universal, for all) password correct, and if so it needs to redirect to main, or if not to display some alert box.
<?php
session_start();
$password = '1234';
if($_POST['password'] == $password){
//Create session
$_SESSION['session'] = 1;
// If correct redirect to main
header('Location: http://www.example.com/main');
exit;
}
else {
// If not correct stay on index (do nothing)
}
?>
Code my main page looks like this. This is where the site should check if user has session and then decide should he be able to see the site or not (if not it should redirect to index for login).
<?php
session_start();
if (!isset($_SESSION["session"]))
{
header("location: http://example.com/index");
}
?>
I Googled everything and came out with no working solution. Is there better way to achive this or can you help me fix it?
So TLDR, how to password protect main page with login (no users, same password for everyone)?
Currently this code doesn't work. When I enter password on index it redirects to main. But main page doesn't have session check working. It simply shows all without redirecting to index for login if user is without session.
Ok.. sorry for my first advice. It is obviously not a solution. But if i understand you correctly. This is my working approach:
index.php
<?php
session_start();
$password = '1234';
// Check if the user is not already logged in
if (isset($_SESSION['login'])) {
header('Location: main.php');
}
// Check if the form is submitted
if (isset($_POST['submit'])) {
if ($_POST['password'] == $password) {
$_SESSION['login'] = true;
header('Location: main.php');
}
}
?>
with form
<form action="" method="post">
<input class="upisnopolje" type="password" name="password" placeholder="Unesite kod" required>
<input class="upisnopolje" id="upisnopoljefix" type="submit" name="submit" value="Ok">
</form>
main.php
<?php
session_start();
// Check if user is logged in
if (!isset($_SESSION["login"])) {
header("location: index.php");
}
if ( isset( $_POST['submit'] ) ) {
unset($_SESSION["login"]);
header("location: index.php");
}
?>
with form to logout
<form action="" method="post">
<input type="submit" name="submit" value="Log out">
</form>
Note that submit button needs to have name="submit" for $_POST['submit'] check.
Hope it helps.
I want to make an PHP session after the visitor enters a valid password so I can display a few hidden links to the visitor, even on page reload.
<?php
if(isset($_POST['submit'])) {
$password = crypt('sumpasswurd', password_hash('rasmuslerdorf', PASSWORD_BCRYPT)); // password
if (hash_equals($password, crypt($_POST['password'], $password))) {
echo 'VALID!';
// CREATE SESSION HERE
} else {
echo 'INVALID';
}
}
if(isset($_SESSION)) echo 'YOU ARE LOGGED IN WITH A VALID PASSWORD!';
?>
<form method="POST" action="">
<input type="text" name="password">
<input type="submit" name="submit" value="OK">
</form>
How can I make this possible? And is the encryption of my form secure?
Manual session starts with session_start() function. Although you need to secure the session by some kind of user indetification logic. For instance, you have user's username and add it as a session variable and afterwards pass some kind of session id to verify that current session user is indeed loged in. Afterwards you have to check those variables in every pageload that is associated with user.
At: // CREATE SESSION HERE you might want to use something like this:
Session_start();
$_SESSION['username'] = $username;
// flollowed by session id logic
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..
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.
I'm looking for a php script so my entire site needs a password to access. I don't want a sql database, I just want one user who's credentials are set in a variable.
I have
config.php
<?php
$secured = false;
$username = "user"; // Set manually by editing config
$password = "pass"; //Set manually by editing config
?>
Then index.html
<form action="auth.php" method="post">
Username: <input type='text' name="user" value='' />
Password: <input type='password' name="password" value='' />
<input type='submit' value='Log in' />
</form>
Then auth.php (This is what I need coded)
<?php
require once "config.php"
If $secured = false the redirect to page1.html
// So if its false don't require authentication at all anywhere on site.
If $secured = true then ask for username and password.
If wrong display error message.
If right redirect to page1.html
?>
That's what I'm trying to achieve. I then also need the login stored as a session variable so it remembers you logged in and checks on each page that you are logged in. Then finally a way to log out. So a button I can just stick somewhere will do the job. Hope this all makes sense.
Question : How does the auth.php script look like?
Thanks
You could use sessions to remember if a user has logged in. To do that, add:
session_start();
in config.php
On every page that requires log in, add this at the top of the script:
require_once('config.php');
if ($secured && (!isset($_SESSION['loggedin']) || !$_SESSION['loggedin'])) {
header('Location: index.html');
exit;
}
Auth.php should look like the following.
<?php
require_once("config.php");
If (!$secured) {
header('Location: page1.html');
exit;
}
if (isset($_POST['user']) && isset($_POST['password'])) {
if ($_POST['user']==$username && $_POST['password']==$password) {
// OK
$_SESSION['loggedin'] = true;
header('Location: page1.html');
exit;
} else {
echo "Bad login credentials. Try again";
}
} else {
// not logging in
header('Location: index.html');
exit;
}
?>
To sign out, just create a script logout.php:
<?php
require_once('config.php');
$_SESSION['loggedin'] = false;
?>
You can use session (see $_SESSION) to store if a user is logged in or not.
Once a user is logged in you can set a session that someone is logged in and then on each visit check if session exists and it is valid (using private salt and hash). If session variable does not exist or is invalid direct user to login page.