I'm sure this is a basic question and I'm sure the answer is basic too - apologies if so, but I'm having trouble linking my practical example to the theory I've read.
I'm using the PHPAuth project for my site's authentication. The bit that's got me confused in the notes is the description for the login method that reads:
Authenticates a user with the system. Note: You need to take the
returned session hash and create the session cookie, the method does
not do this for you.
If a successful login returns:
Array ( [error] =>
[message] => You are now logged in.
[hash] => 374d0de4f97b96b6665c23aa0998dbae1f790fe6
[expire] => 0
)
What do I actually do with this information to allow the next page to see that a user is logged in?
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php");
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
if (!$auth->isLogged()) {
header('HTTP/1.0 403 Forbidden');
echo "Forbidden";
exit();
}
echo "you are logged in";
?>
I am assuming the above code will handle the session cookie as this is code is almost exactly as the example given by the PHPAuth project so specifically, I'm asking what is meant by the bold text in the above quote.
FYI, the class functions for checking the cooking look like this:
/**
* Returns is user logged in
* #return boolean
*/
public function isLogged() {
return (isset($_COOKIE[$this->config->cookie_name]) && $this->checkSession($_COOKIE[$this->config->cookie_name]));
}
/**
* Returns current session hash
* #return string
*/
public function getSessionHash(){
return $_COOKIE[$this->config->cookie_name];
}
My previous answer answers my question, but I'm posting this answer in the hope that it may help someone else using the PHPAuth project.
This is my login page:
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
if ($auth->isLogged()) {
echo "You are already signed up and logged in";
exit();
}
$msg = null;
$showform = true;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//check for errors
if (empty($_POST["email"]) ||
empty($_POST["pwd"]) ) {
$msg = "All fields are required.";
} else { //all good - proceed
$result = $auth->login($_POST["email"], $_POST["pwd"]);
//check for success
if ($result["error"] == 1) {
$msg = $result["message"];
} else {
//success
$msg = $result["message"];
$showform = false;
setcookie($config->cookie_name, $result['hash'], time()+3600, "/"); //NOTE: the time can be set with config from the cookie_forget or cookie_remember settings in the PHPAuth config table
}
}
}
?>
<html>
<head></head>
<body>
<?php
if ($showform == true) { ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<div>
<label for="email">Email:</label>
<div>
<input type="email" name="email" id="email" placeholder="Enter email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
</div>
</div>
<div>
<label for="pwd">Password:</label>
<div>
<input type="password" name="pwd" id="pwd" placeholder="Enter password">
</div>
</div>
<div>
<button type="submit" name="submit">Submit</button>
</div>
<?php echo $msg; ?>
</form><?php
} else {
echo $msg . '<br />';
}
?>
</body>
</html>
This is a secured page:
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
if (!$auth->isLogged()) {
header('HTTP/1.0 403 Forbidden');
echo "Forbidden";
exit();
}
echo "You are logged in";
?>
And this is a logout script:
<?php
require 'vendor/autoload.php';
include("dbconnect-user.php"); //this contains my own database connection code
$config = new PHPAuth\Config($dbh);
$auth = new PHPAuth\Auth($dbh, $config);
echo $auth->logout($_COOKIE['authID']);
?>
The basic answer appears to be this:
Obviously, we need to create the session cookie. In this particular case, the cookie name needs to be the name stored in the config db, "authID".
To do this, I just need to use setcookie see http://php.net/manual/en/function.setcookie.php
In my testing example, on a successful login, I set the cookie and then redirect on a script page like this:
setcookie('authID', $_GET['h'], time() + (86400 * 30), "/");
header('Location: main.php');
Related
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()"
i have this code to verify if users have Administrator account to backoffice of my website, but if user don't have it don't redirect user to ..index.php. He stay in this page but no content is shown.
Code of verification
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
}
else
{
echo "<script>alert(\"Area Restrita\");</scrpit>";
header("Location: ../index.php");
}
?>
In this page, (header) i call this file to verify session.
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
header("Location: ../index.php"); is not going to stop the rest of the code from running - if you just want to redirect him you should die(); or exit; right after you send the Location header
The alert part before the Location header is also unnecessary because the browser will redirect the user before he'll be able to see the alert. and also it is forbidden to call header function after you sent something to the output (for example, like you did with echo)
Another thing that you should consider - is the security issues that raised from validating user solely by looking at values in the $_SESSION - this means - that if someone is logged - you are not able to log him out until the session expires
The better way is to keep some token in the $_SESSION and save the status of the user in the database - that way, you can change his status directly from the DB without relying on the session/changing code
Your index file:
<?php
session_start();
require_once "../config.php";
require "verificar.php";
?>
<div id="header">
<img src="img/logo.png">
</div>
Your verification file:
<?php
$Usuario = isset($_SESSION["Usuario"]) ? $_SESSION["Usuario"]: '';
$Rank = isset($_SESSION['Rank']) ? $_SESSION['Rank'] : '';
if ($Usuario != '' && $Rank == 'Administrador'){
// do some action for administrator
}
else
{
header("Location: ../index.php");
exit();
//echo "<script>alert(\"Area Restrita\");</scrpit>"; <-- you don't need this here
}
?>
Note, that I commented echo. You mustn't output anything before header. If you will output something (and you do in your example) you will get headers already sent error.
Your main mistake is you output something first and after that tried to redirect.
Anyway, I think better to use a bit another approach.
Form and form handler:
<?
$username = $_POST['username'];
$password = $_POST['password'];
// here is some query which will check if this user with this password exists and get the role of the user
// if exists $userExists = true; else $userExists = false;
if($userExists) {
$_SESSION['userLoggedIn'] = true;
if($role == 'administrator') {
$_SESSION['isAdministrator'] = true;
}
else
{
$_SESSION['isAdministrator'] = false;
}
header('Location: index.php');
exit(); // <-- don't forget this
}
else
{
// handler for bad user/password
}
?>
<form action='' method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
</form>
Now, pages which are restricted will start from this code:
<?
$isAdministrator = $_SESSION['isAdministrator'];
if(!$isAdministrator) {
ban_ban_ban();
die('bye bye');
}
// content for administrator
?>
NOTE: This is just example, don't forget to add some check everywhere!!!!!11
But, as you wish :) Hope, this will help you.
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 trying to get a login on a website where it connects to the database, checks against it, but the redirect isn't working (login.php to loggedin.php). I am appalling at proof reading my own code and have been going round in circles for a while. If someone could assist I would be very grateful! Thank you in advance.
Login_page.inc.php
<?php # Script 11.1 - login_page.inc.php
// this page prints any errors associated with logging in
//and creates te entire login page, including the fom
//include the header:
$page_title = 'Login';
include ('includes/header.html');
//print any error messages if they exist:
if (!empty($errors))
{
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:</br>';
foreach ($errors as $msg)
{
echo "- $msg</br>\n";
}
echo '</p><p>Please try again.</p>';
}
//display form
?>
<h1>Login</h1>
<form action=login.php" method="post">
<p>Email Address: <input type="text" name="email" size="20" maxlength="80"/></p>
<p>Password: <input type="password" name="pass" size="20" maxlength="20"/></p>
<p><input type="submit" name="submit" value="Login"/></p>
<input type="hidden" name="submitted" value="TRUE"/>
</form>
<?php //include the footer:
include ('includes/footer.html');
?>
Loggedin.php
<?php # loggedin.php
//this is where the user is directed from login.php
session_start();
//if no cookie is present redirect the user:
//if (!isset($_COOKIE['user_id']))
if (!isset($_SESSION['user_id']))
{
//the functions need to create an absolute url
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit(); //exit script
}
//set the page title and include the header
$page_title = 'Logged in.';
include ('includes/header.html');
//welcome message
echo "<h1>Logged in!</h1>
<p>You have successfully logged in, {$_SESSION['first_name']}!</p>
<p>Logout</p>";
include ('includes/footer.html');
?>
Login.php
<?php # login.php
//this page processes the login form submission
//upon successful login the user's redirected
//two include files are needed for this
//send nothing to the web browser prior to the setcookie() lines
//check if the form has been submitted:
if (isset($_POST['submitted']))
{
//for processing the login:
require_once ('includes/login_functions.inc.php');
//need the database connection:
require_once ('includes/mysqli_connect.php');
//check the login
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);
if($check)
{
/*ok, set cookies to last one hour after it is set
setcookie ('user_id', $data ['user_id'], time()+3600, '/', '', 0, 0);
setcookie ('first_name', $data ['first_name'], time()+3600, '/', '', 0, 0);*/
session_start();
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['first_name'] = $data['first_name'];
//redirect
$url = absolute_url ('loggedin.php');
header("Location: $url");
exit(); //quit the script
}
else
{
//assign errors to $data for error reporting in the login_page.inc.php
$errors = $data;
}
mysqli_close($dbc); //close the database connection
} //end of main submit condition
include ('includes/login_page.inc.php');
?>
Login_functions.php
<?php #- login_functions.inc.php
//this page defines two functions used by the login/logout process.
/*this function determines and returns an absolte URL
*takes one argument: the page that concludes the URL
*the arguement defaults to index.php
*/
function absolute_url ($page = 'index.php')
{
//start defining the URL. . .
//URL is http:// plus the host name plus current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
//remove any trailing slashes:
$url = rtrim($url, '/\\');
//adding the page. . .
$url.= '/' . $page;
//return to the url
return $url;
} //end of the absolute_url function
/* this function validates the form data (the email address and password)
*if both are present the database is queried
*this function requires a database connection
* the function returns an array of information. including:
* - a TRUE or FALSE variable indicating a success or failure
* - an array of either errors or the database return result
*/
function check_login($dbc, $email = '', $pass = '')
{
$errors = array(); //starting error array
//validate email address
if (empty($email))
{
$errors[] = 'You forgot to enter your email address.';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($email));
}
//validate the password
if (empty($pass))
{
$errors[] = 'You forgot to enter your password.';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($pass));
}
if (empty($errors))
{
/*if everything's okay
*retrieve the user_id and the first_name for that
*email+password combination:
*/
$q = "SELECT user_id, first_name FROM site_users WHERE email='$e' AND pass=SHA1('$p')";
$r = #mysqli_query ($dbc, $q); //run the query
//check the result and making sure that both fields are in the same row
if(mysqli_num_rows($r) ==1)
{
//fetch the record
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
//return true and the record:
return array(true, $row);
}
else
{
//not a match
$errors[] = 'The email address and password entered do not match those on file.';
}
}//end of empty($errors) IF.
//return false and the errors:
return array(false, $errors);
} //end of check_login() function
?>
If any of the files contains any code that gets sent to the browser, PHP sends all the headers automatically. After the headers have been sent, you can no longer send new headers, and it drops your Location: header. PHP should be throwing a notice, look for it in your logs and/or set the correct error_reporting flags.
This includes newlines or spaces or whatever that is after an ?> tag block.
There is nothing wrong with your script from what i can see ... here but am not sure of the content of
includes/header.html
index.php
You need to also replace
<form action=login.php" method="post">
with
<form action="login.php" method="post">
If you can paste the error you are seeing .. maybe i can help you better
Thanks
:)
Don't include any blank line before your header('Location: $url'). Because this prevents sending header and you are not able to get redirect to place where you want to be.
The issue was within the SHA1 talking to the database, where by SHA1 is a (40) strong and the database was set to (20). An annoying issue but it has not been resolved. Var_dump was used to talk to the database to prove that the information being entered was correct, it did however show that the password held in the database was (20) and the password entered for login was (40).
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.