I am using a login system that works well. I am also using a comment system. The comment function does not show up unless the user is logged in (as shown in commentformonoff.php below).
When a user makes a comment, the info is passed from the function "show_commentbox" to the file comments2a.php. Then, the info is passed to the file comments2.php.
When the site is first pulled up on a browser, after logging in and making a comment, the user is logged out. After logging in a second time during the same browser session, the user is no longer logged out after making a comment.
How can I keep the user logged in after making the first comment?
Thanks in advance,
John
Login function:
function show_loginform($disabled = false)
{
echo '<form name="login-form" id="login-form" method="post" action="./index.php?'.$_SERVER['QUERY_STRING'].'">
<div class="usernameformtext"><label title="Username">Username: </label></div>
<div class="usernameformfield"><input tabindex="1" accesskey="u" name="username" type="text" maxlength="30" id="username" /></div>
<div class="passwordformtext"><label title="Password">Password: </label></div>
<div class="passwordformfield"><input tabindex="2" accesskey="p" name="password" type="password" maxlength="15" id="password" /></div>
<div class="registertext">Register</div>
<div class="lostpasswordtext">Lost password?</div>
<p class="loginbutton"><input tabindex="3" accesskey="l" type="submit" name="cmdlogin" value="Login" ';
if ($disabled == true)
{
echo 'disabled="disabled"';
}
echo ' /></p></form>';
}
Commentformonoff.php:
<?php
if (!isLoggedIn())
{
if (isset($_POST['cmdlogin']))
{
if (checkLogin($_POST['username'], $_POST['password']))
{
show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl);
} else
{
echo "<div class='logintocomment'>Login to comment</div>";
}
} else
{
echo "<div class='logintocomment'>Login to comment</div>";
}
} else
{
show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl);
}
?>
Function "show_commentbox":
function show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl)
{
echo '<form action="http://www...com/.../comments/comments2a.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$_SESSION['username'].'" name="u">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<input type="hidden" value="'.stripslashes($submission).'" name="submission">
<input type="hidden" value="'.$url.'" name="url">
<input type="hidden" value="'.$submittor.'" name="submittor">
<input type="hidden" value="'.$submissiondate.'" name="submissiondate">
<input type="hidden" value="'.$countcomments.'" name="countcomments">
<input type="hidden" value="'.$dispurl.'" name="dispurl">
<label class="addacomment" for="title">Add a comment:</label>
<textarea class="checkMax" name="comment" type="comment" id="comment" maxlength="1000"></textarea>
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
}
Included in comments2a.php:
$uid = mysql_real_escape_string($_POST['uid']);
$u = mysql_real_escape_string($_POST['u']);
$query = sprintf("INSERT INTO comment VALUES (NULL, %d, %d, '%s', NULL)", $uid, $subid, $comment);
mysql_query($query) or die(mysql_error());
$lastcommentid = mysql_insert_id();
header("Location: comments2.php?submission=".$submission."&submissionid=".$submissionid."&url=".$url."&submissiondate=".$submissiondate."&comment=".$comment."&subid=".$subid."&uid=".$uid."&u=".$u."&submittor=".$submittor."&countcomments=".$countcomments."&dispurl=".$dispurl."#comment-$lastcommentid");
exit();
Included in comments2.php:
if($_SERVER['REQUEST_METHOD'] == "POST"){header('Location: http://www...com/.../comments/comments2.php?submission='.$submission.'&submissionid='.$submissionid.'&url='.$url.'&submissiondate='.$submissiondate.'&submittor='.$submittor.'&countcomments='.$countcomments.'&dispurl='.$dispurl.'');}
$uid = mysql_real_escape_string($_GET['uid']);
$u = mysql_real_escape_string($_GET['u']);
EDIT: Someone said that these might be useful so I'm posting them.
function isLoggedIn()
{
if (session_is_registered('loginid') && session_is_registered('username'))
{
return true; // the user is loged in
} else
{
return false; // not logged in
}
return false;
}
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
if (!valid_username($u) || !valid_password($p) || !user_exists($u))
{
return false; // the name was not valid, or the password, or the username did not exist
}
//Now let us look for the user in the database.
$query = sprintf("
SELECT loginid
FROM login
WHERE
username = '%s' AND password = '%s'
AND disabled = 0 AND activated = 1
LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
$result = mysql_query($query);
// If the database returns a 0 as result we know the login information is incorrect.
// If the database returns a 1 as result we know the login was correct and we proceed.
// If the database returns a result > 1 there are multple users
// with the same username and password, so the login will fail.
if (mysql_num_rows($result) != 1)
{
return false;
} else
{
// Login was successfull
$row = mysql_fetch_array($result);
// Save the user ID for use later
$_SESSION['loginid'] = $row['loginid'];
// Save the username for use later
$_SESSION['username'] = $u;
// Now we show the userbox
return true;
}
return false;
}
I think your error is in isLoggedIn() could you post this. Because you have two paths to write the comment box. Which could mean that on login the first path is chosen, but on refresh, when you were supposed to get to the second path it doesn't.
The error could also be in checkLogin, not setting a session variable?
please post both isLoggedIn() and checkLogin() :)
<?php
if (!isLoggedIn()) // most likely the place of error
{
if (isset($_POST['cmdlogin']))
{
if (checkLogin($_POST['username'], $_POST['password'])) // setting session variable correctly?
{
// path one
// are you supposed to set some session variables here? or in checkLogin()?
show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl);
} else
{
echo "Login to comment";
}
} else
{
echo "Login to comment";
}
} else
{
// path two
show_commentbox($submissionid, $submission, $url, $submittor, $submissiondate, $countcomments, $dispurl);
}
?>
Edit:
In isLoggedIn() use isset() instead of session_is_registered(). session_is_registered() is deprecated as of PHP 5.3.0.
if(isset($_SESSION['loginid']) && isset($_SESSION['username'])
On the bottom of the file CommentOnOff.php can you put in this code?
var_dump($_SESSION)
It should print out everything that is contained in the session. Then you can see if the loginind and username is actually stored in the session :)
It would be nice to see more about what's happening. These are just the snippets you thought might be important, not the whole thing.
There are some questions related to the code you submitted:
- How does the commentformonoff.php connects to the other php files you submitted?
- What happens in isLoggedIn() and checkLogin() functions?
- Why do you split the functions to comments2.php and comments2a.php? Redirecting without a reason just adds delay to the execution. Is there a reason you cannot process the request there?
- the comment values goes directly into the query without sanitation in comments2a.php, that is a serious security breach.
- In comments2a.php you create a redirection and pass variables by GET and in comments2.php you check for POST and redirect if a post request is found. Why do you do this?
Check out Smarty if you can, that's not a big overhead and you don't have to write functions spitting out html forms. Or, you could include html code directly in the code if there are no parameters inside, with closing and reopening the php tags.
I had very similar symptoms in a web app I was developing.
Try adding a favicon.ico file (an empty one is OK) to the root directory of your application.
These are the symptoms that I was experiencing...
Firefox:
User logs in, first "logged in" page appears. User clicks link and is no longer logged in. User logs in again and gets first "logged in" page. User clicks link and is still logged in. User continues to use the application as logged in user without problem.
Chrome:
User logs in, first "logged in" page appears. User clicks link and is no longer logged in. User logs in again and gets first "logged in" page. User clicks link and is logged out again. User simply cannot stay logged in after first "logged in" page.
I checked the error logs and saw that every request was looking to get the favicon.ico file. I added an empty favicon.ico file to my applications root directory and the problem stopped.
Related
I have a very simple php single page, that requires the user to insert a specific username and pass in order to access its contents.
It generates a cookie that allows the user to access that page for one day.
If the user is logged in, the list of contents appear. If it's not, it shows the form.
It is all inside a single index.php page.
This single "protected" page contains a form where the user can put some information and save it. After the user logs in, all the content is shown as intended. But when the user tries to submit that form and reloads the page (the new content should be added to that page), it gets kicked out and the information contained in the form gets lost, and it's not saved.
This are the specific parts of the index.php page:
<?php session_start(); ?>
<!DOCTYPE html>
[...]
<?php
if(isset($_POST['loguearse'])) {
$_SESSION['user']=strip_tags($_POST['user']);
$_SESSION['pass']=strip_tags($_POST['pass']);
if($_SESSION['user'] == 'myuser' && $_SESSION['pass'] == 'mypass') {
if (isset($_SESSION['user'])) {
session_start();
setcookie ("usuario",$_POST['user'], time()+24*60*60);
setcookie ("clave",$_POST['pass'], time()+24*60*60);
}
[HERE IT GOES THE CONTENT THAT WORKS OK IF I STRIP THE LOGIN CONTROL]
}
} else {
setcookie("usuario","");
setcookie("clave","");
echo '
<form method="post">
<div class="form-group">
<input type="text" class="form-control" name="user" id="user" placeholder="Usuario">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" placeholder="clave">
</div>
</div>
<div class="modal-footer">
<input type="submit" name="loguearse" class="btn btn-primary">
</div>
</div>
</form>
';
echo 'No puedes entrar sin poner la clave correcta!';
}
?>
My question is: How do I keep that user logged in and with an active session for 24 hours?
Your testing order is the problem here. You are originally testing for the POST variable, not the SESSION variable. Try this:
Test for logout to see if the user tried to logout. If so, delete the session.
Test for the session variables to indicate they're already logged in.
IF 1 and 2 are false, test for login. If so, initialize session.
It's the way you construct your if-conditions. Every time the user doesn't submit a post form you overwrite the cookie. The condition isset($_SESSION['user']) has to be on the highest level (at first) and then the post form check.
Also you run twice session_start(), one time is enough.
I use this for this exact thing and just include this in the header of any page.
<?php
#session_start();
// DB DEFINITIONS
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$db = db_connect();
if(isset($_GET['logout'])){
session_unset();
session_destroy();
if (isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
setcookie("cookuhash", "", time()-2592000,"/");
setcookie("cookfhash", "", time()-2592000,"/");
$uhash=$db->real_escape_string($_COOKIE['cookuhash']);
$fhash=$db->real_escape_string($_COOKIE['cookfhash']);
$db->query("DELETE FROM tblsessions WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
}
header("Location: /index.php");
exit();
}
if(!isset($_SESSION['loggedIn'])){
$_SESSION['loggedIn']=false;
$_SESSION['username'] = 'Anonymous';
$_SESSION['userid'] = 0;
$_SESSION['userlevel'] = 0;
$_SESSION['formToken'] = sha1(microtime());
}
if (!$_SESSION['loggedIn'] && isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
$uhash=$db->real_escape_string($_COOKIE['cookuhash']);
$fhash=$db->real_escape_string($_COOKIE['cookfhash']);
$result = $db->prepare("SELECT u.id,uname, lvl, user_lvl_expires FROM tblusers u LEFT JOIN tblsessions s ON s.USER_ID=u.ID WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
$result->execute();
$result->bind_result($id,$uname,$ads,$lvl,$expires);
$result->store_result();
if($result->num_rows > 0){
while ($result->fetch()) {
$_SESSION['loggedIn']=true;
$_SESSION['username'] = $uname;
$_SESSION['userid'] = $id;
$_SESSION['userlevel'] = $lvl;
$_SESSION['expires'] = $expires;
$_SESSION['formToken'] = sha1(microtime());
}
}
}
?>
Then in any page, just check:
#session_start();
if((!isset($_SESSION['loggedIn']) || $_SESSION['loggedIn']==0) && !isset($_COOKIE['cookuhash'])){
header("Location: /login.php");
exit();
}
I have been working on CS50's problem set 7, in which we have to make a financial website using MVC. I completed the website and it is working absolutely fine on my local machine.
But when I upload the files to hosting (free) service's server and try to access it I get a Redirect Loop error. Here is the link to it: http://ghazilajpal.byethost6.com/finance/public/
Here is code of login.php:
<?php
// configuration
require("../includes/config.php");
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
// render form
render("login_form.php", ["title" => "Log In"]);
}
// else if user reached page via POST (as by submitting a form via POST)
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// validate submission
if (empty($_POST["username"]))
{
apologize("You must provide your username.");
}
else if (empty($_POST["password"]))
{
apologize("You must provide your password.");
}
// query database for user
$rows = query("SELECT * FROM users WHERE username = ?", $_POST["username"]);
// if we found user, check password
if (count($rows) == 1)
{
// first (and only) row
$row = $rows[0];
// compare hash of user's input against hash that's in database
if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
{
// remember that user's now logged in by storing user's ID in session
$_SESSION["id"] = $row["id"];
$_SESSION["cash"] = $row["cash"];
// redirect to index.php (portfolio)
redirect("/");
}
}
// else apologize
apologize("Invalid username and/or password.");
}
?>
Update
Here is login_form.php:
<form action="login.php" method="post">
<fieldset>
<div class="form-group">
<input autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Log In</button>
</div>
</fieldset>
</form>
<div>
or register for an account
</div>
And this is config.php. This also has a redirect:
<?php
/**
* config.php
*
* Computer Science 50
* Problem Set 7
*
* Configures pages.
*/
// display errors, warnings, and notices
ini_set("display_errors", true);
error_reporting(E_ALL);
// requirements
require("constants.php");
require("functions.php");
// enable sessions
session_start();
// require authentication for all pages except /login.php, /logout.php, and /register.php
if (!in_array($_SERVER["PHP_SELF"], ["/login.php", "/logout.php", "/register.php"]))
{
if (empty($_SESSION["id"]))
{
redirect("login.php");
}
}
?>
I hope its easy to understand. I don't know where the problem lies and how to fix it.
I could have asked it on cs50.stackexchange.com but a similar question is already there with no answer.
Is it coming in this code block always?
if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
{
// remember that user's now logged in by storing user's ID in session
$_SESSION["id"] = $row["id"];
$_SESSION["cash"] = $row["cash"];
// redirect to index.php (portfolio)
redirect("/");
}
if yes then here have a probelm.
change redirect with die(); to verify.
And Please provide some more inputs from you to clarify more.
I did some debugging using bhushanRJ's advice of using die (). And found out that the issue is with URLs. So using /finance/public/login.php instead of just login.php (same for other array items) solved the issue.
However CSS and JS files weren't loading. Similarly, fixing their URLs in templates fixed the issue.
When I got a loop it was because I hadn't started the session by putting "session_start()"
OK. I have a page called plans.php, inside I have three links (Plan 1, Plan 2, Plan 3). Each link has its own page and it redirects to login page (login.php, which works fine). So if the user is not logged in when they click lets say on "Plan 2" it will force the user to login so they can see the desired page, all depends of what "Plan" the user chooses.
PROBLEM:
I'm having a hard time redirecting the user back to the "desired Plan (URL)".
Solution:
If the user chooses "Plan 1 or Plan 2 (whatever plan)" then it will force user to login (I have that working fine), after user logs in successfully the user has to be redirected to their respective "Plan page".
If any is familiar with this issue please help.
plans.php
Plan 1
Plan 2
Plan 3
plan-2.php
<?php
ob_start();
include "header.php";
if(!$current_user) {
require_login();
}
ob_end_flush();
?>
HTML code:
What the user is going to see after login page.
<p>Hello, you have been redirected to "Plan 2"</p>
login.php
<?php
ob_start();
include "header.php";
if($current_user) {
req_logout(); }
ob_end_flush();
?>
HTML code:
<form action="authenticate.php" method="POST">
<label for="email">Email</label><br/>
<input type"text" class="input" name="username" id="username" />
<label for="password">Password</label><br/>
<input name="password" type="password" class="input" id="password"/>
<input type="submit" value="Sign In" class="submit"/>
</form>
This file verifies user credentials where the login form submits to.
authenticate.php
<?php
session_start();
require_once "db.php";
db_connect();
require_once "auth.php";
$user_id = credentials_valid($_POST['username'], $_POST['password']);
if($user_id){
log_in($user_id);
if($_SESSION['redirect_to']){
header("Location: " . $_SESSION['redirect_to']);
unset($_SESSION['redirect_to']);
}else{
// Default page after user logs in.
header("Location: manage.php");
}
}else{
header("Location: login.php?error=1");
exit("You are being redirected");
}
?>
I have some PHP functions in this file.
auth.php
// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}
// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
if($_SESSION['user_id']){
$user_id = intval($_SESSION['user_id']);
$query = "SELECT *
FROM `********`
WHERE `id` = $user_id";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$current_user = mysql_fetch_assoc($result);
return $current_user;
}
}
}
return $current_user;
}
// Requires a current user (Restrict Access to Page)
function require_login(){
if(!$current_user){
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header('Location: signin.php');
exit("You must log in.");
}
}
Try to send a parameter when a user clicks on a plan link. Pass or save the parameter and after successful login, use that parameter to redirect to the proper page.
in plan-2.php
session_start();
$_SESSION['redirect_to']="plan-2.php";
EDIT:
Here is complete solution using parameter sending via GET and POST (as I have been asked for):
plans.php
Plan 1
Plan 2
Plan 3
plan.php
<?php
ob_start();
$getbackURLid=$_GET['no'];
include "header.php";
if(!$current_user) {
require_login($getbackURLid);
}
ob_end_flush();
?>
signin.php
<?php
ob_start();
include "header.php";
if($current_user) {
req_logout(); }
ob_end_flush();
?>
HTML code:
<form action="authenticate.php" method="POST">
<label for="email">Email</label><br/>
<input type"text" class="input" name="username" id="username" />
<label for="password">Password</label><br/>
<input name="password" type="password" class="input" id="password"/>
<input type"hidden" name="url" value="<?php echo $_GET['url'];?>" />
<input type="submit" value="Sign In" class="submit"/>
</form>
authenticate.php
<?php
session_start();
require_once "db.php";
db_connect();
require_once "auth.php";
$user_id = credentials_valid($_POST['username'], $_POST['password']);
if($user_id){
log_in($user_id);
if($_POST['url']){
header("Location: plan.php?no=".$_POST['url']);
unset($_SESSION['redirect_to']);
}else{
// Default page after user logs in.
header("Location: manage.php");
}
}else{
header("Location: login.php?error=1");
exit("You are being redirected");
}
?>
auth.php
// Logs into the user $user
function log_in($user_id){
$_SESSION['user_id'] = $user_id;
}
// Returns the currently logged in user (if any)
function current_user(){
static $current_user;
if(!$current_user){
if($_SESSION['user_id']){
$user_id = intval($_SESSION['user_id']);
$query = "SELECT *
FROM `********`
WHERE `id` = $user_id";
$result = mysql_query($query);
if(mysql_num_rows($result)){
$current_user = mysql_fetch_assoc($result);
return $current_user;
}
}
}
return $current_user;
}
// Requires a current user (Restrict Access to Page)
function require_login($getbackURLid){
if(!$current_user){
$_SESSION['redirect_to'] = $_SERVER['REQUEST_URI'];
header('Location: signin.php?url=$getbackURLid');
exit("You must log in.");
}
}
Since some popular browsers (like Chrome) cache server redirect responses, if you do a server redirect, the requested page will always redirect to the same page as the first redirect the browser encountered.
To solve this, you validation PHP page should contains the following redirection:
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
// Check if the session's user is logged in properly
$redirect = "";
if (!$_SESSION['current_user']) {
$target_page= "http://www.myserver.com/login?sender=" + urlencode(curPageURL());
echo "<html>";
echo " <head>";
echo " <script>";
echo " window.location = '", $target_page, "';";
echo " </script>";
echo " </head>";
echo " <body></body>";
echo "</html>"
} else {
?>
<html>
<head>
</head>
<body>
<!-- put your page html here -->
</body>
</html>
<?php
}
?>
Please note that I'm not a PHP developper, my code may contains syntax errors and must be revised properly.
So... yeah, the code may look a little bit crappy but the important thing to remember is to not use the http response redirection. I tried all possible ways to disable response caching but chrome don't care at all. The only safe way I found is to do the redirection using javascript. I did not try the META http-equiv="refresh" way though. I guess it's safe as well since we see that often.
Another thing to remember is to avoid rendering your sensitive page content if the user is not logged in.
With that in mind, you should be good to go.
Hope it helps!
I'm making a login system with php, and when I submit the correct information, it set's a cookie. the form action sends to the same page, wich has an isset cookie verification on top, but since cookies need a refresh after they're set, you need to refresh page another time so it can notice that cookies are there.
what's a workaround for it? here's my code (where username and password are "admin" just as a placeholder. when I get the system working, I'll pull values from database.)
<?php
if(isset($_COOKIE['user']))
{
echo "Hello, administrator.<br />";
echo "<a href=?logout=yes>logout</a>";
if(isset($_GET['logout']))
{
setcookie("user", $_POST['username'], time() - 3600);
}
}
else
{
if (isset($_POST['submit']))
{
if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
setcookie("user", $_POST['username'], time() + 3600);
}
else
{
echo "empty field or wrong user/pass.";
}
}
else
{
echo "nothing submitted. show form.";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
Unless you absolutely need to use a custom cookie, I would suggest to use the $_SESSION global instead. $_SESSION data is available as soon as you set it. But its more important feature is that the data is not stored on the client. What that mean in plain is that the user can never access its data. So it is harder to hack your login system. With a cookie, as other have pointed out, anybody can read and edit the data!
session_start();
if (isset($_GET['logout']))
{
unset($_SESSION['username']);
}
if ($_SESSION['username'] == 'admin')
{
echo "hello admin!";
}
else if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
$_SESSION['username'] = $_POST['username'];
}
To use the $_SESSION globals, you need to put session_start() at the beginning of your script (before sending any data). It should solve your problem of redirection at the same time. Note that behind the scene, $_SESSION use a small cookie, but you don't really have to think about it. It only contain a small id.
more information on session
http://www.php.net/manual/en/book.session.php
PS : to be honest, I would still use a redirect here. When you POST a form and press the back button, the browser ask you to send the data again and its annoying. Using a redirect with header("Location: " . $newUrl); remove that annoyance. But just my 2 cents.
$loggedin = false;
if(isset($_POST['submit'])) {
// Do login checking and set cookies
$loggedin = true; // if the case
}else if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
// Check if valid login
$loggedin = true; // if the case
}else{
// They are not logged in.
}
Then use the veriable $loggedin to see if they are logged in. I suggest making a user class though to handle this, so do you keep using the same code over and over again in your files.
You can make your own function to set cookies, ie:
function my_setcookie($name,$value,$expire){
$_COOKIE[$name] = $value;
return setcookie($name,$value,$expire);
}
But better idea is to redirect user after successful 'POST' request, so if the page is refreshed, browser won't complain about resending POST data.
I am using a login system that malfunctions when a fresh browser session is opened. It appears to happen across all browsers. Here's what happens:
I open a new browser session.
I enter a user name and password, and I am logged in just fine.
I navigate to another page (any page), and I am no longer logged in (this is bad - not what I want).
I enter a user name and password, and I am logged in just fine.
I navigate elsewhere, and I am still logged in (this is good - this is what I want).
During the same browser session, the log-in / log-out works fine. I can even log in with different usernames and navigate freely and all functions as it should.
This happens every time I open a new browser window. So basically, I have to do the initial log-in twice for the first username I user per browser session. Then, everything works just fine, even for multiple users.
Any idea why this might be happening?
The code I am using is below.
Thanks in advance,
John
login.php:
<?php
if (!isLoggedIn())
{
// user is not logged in.
if (isset($_POST['cmdlogin']))
{
// retrieve the username and password sent from login form & check the login.
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
} else
{
echo "Incorrect Login information !";
show_loginform();
}
} else
{
// User is not logged in and has not pressed the login button
// so we show him the loginform
show_loginform();
}
} else
{
// The user is already loggedin, so we show the userbox.
show_userbox();
}
?>
Show Login Form Function:
function show_loginform($disabled = false)
{
echo '<form name="login-form" id="login-form" method="post" action="./index.php?'.$_SERVER['QUERY_STRING'].'">
<div class="usernameformtext"><label title="Username">Username: </label></div>
<div class="usernameformfield"><input tabindex="1" accesskey="u" name="username" type="text" maxlength="30" id="username" /></div>
<div class="passwordformtext"><label title="Password">Password: </label></div>
<div class="passwordformfield"><input tabindex="2" accesskey="p" name="password" type="password" maxlength="15" id="password" /></div>
<div class="registertext">Register</div>
<div class="lostpasswordtext">Lost password?</div>
<p class="loginbutton"><input tabindex="3" accesskey="l" type="submit" name="cmdlogin" value="Login" ';
if ($disabled == true)
{
echo 'disabled="disabled"';
}
echo ' /></p></form>';
}
Login functions:
<?php
#### Login Functions #####
function isLoggedIn()
{
if (session_is_registered('loginid') && session_is_registered('username'))
{
return true; // the user is loged in
} else
{
return false; // not logged in
}
return false;
}
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
if (!valid_username($u) || !valid_password($p) || !user_exists($u))
{
return false; // the name was not valid, or the password, or the username did not exist
}
//Now let us look for the user in the database.
$query = sprintf("
SELECT loginid
FROM login
WHERE
username = '%s' AND password = '%s'
AND disabled = 0 AND activated = 1
LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
$result = mysql_query($query);
// If the database returns a 0 as result we know the login information is incorrect.
// If the database returns a 1 as result we know the login was correct and we proceed.
// If the database returns a result > 1 there are multple users
// with the same username and password, so the login will fail.
if (mysql_num_rows($result) != 1)
{
return false;
} else
{
// Login was successfull
$row = mysql_fetch_array($result);
// Save the user ID for use later
$_SESSION['loginid'] = $row['loginid'];
// Save the username for use later
$_SESSION['username'] = $u;
// Now we show the userbox
return true;
}
return false;
}
?>
Can you try this:
function isLoggedIn()
{
if (isset($_SESSION['loginid']) && isset($_SESSION['username']))
{
return true; // the user is loged in
}
else
{
return false; // not logged in
}
return false;
}