Redirect loop issue in PHP website - php

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()"

Related

PHP: Setting the session information in a cookie won't be kept after page reloads?

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();
}

How to secure page with access code

Okey guys , i try to secure page with access code ,but page is not secrued if some people write in url pagename.php page is loading without checked my code is. Code is work after put correct access code redirect to my page but , page is not secured client visit page without code after write in url my page .....
<?php
include ('modules/conf.php');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$secretcode = mysqli_real_escape_string($db,$_POST['secretcode']);
$sql = "SELECT * FROM password WHERE password = '$secretcode'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
if($count == 1) {
$_SESSION['login_user'] = $secretcode;
session_start();
header("location: question.php");
}else {
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("", "Съжеляваме вашият код е невалиден");';
echo '}, 1000);</script>';
}
}
?>
<div class="section">
<div class="container-fluid gamebox">
<div class="row">
<div class="col-md-6">
<div class="secretcode">
<h1 class="text-center">въведете код от брошурата</h1>
<form action="" method="post" class="formsecretcode text-center">
<input type="secretcode" id="codeverify" name="secretcode" placeholder="въведете вашият код">
<input type="submit" class="buttonsubmit" name="submit" value="провери код">
</form>
</div>
</div>
As I stated in comments and seeing that nobody posted an answer so far, am submitting the following.
Check to see if the session is set (with an optional "if { equal to something }"), and if not, else { kick them out }.
The logic is, and to be part of every page using sessions that you wish to protect and assuming $secretcode equals 12345 as an example:
<?php
session_start();
if (isset($_SESSION['login_user']) && $_SESSION['login_user'] == '12345'){
// Do something
}
else {
// Do something else
}
It's also best to add exit; after header, otherwise your code may want to continue executing.
Reference:
http://php.net/manual/en/function.header.php
Footnotes:
You don't need to use session_start(); twice as that may trigger that the session was already started.
Use it once and at the "top" of every page, while making sure you're not outputting before header.
References:
http://php.net/manual/en/features.sessions.php
How to fix "Headers already sent" error in PHP
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Additional notes:
You could optionally check for both a username and secret word in the query which makes it a bit more unique.
$username = "Johnny B. Good";
$sql = "SELECT * FROM password
WHERE username = '$username'
AND password = '$secretcode'";
Unless you're only checking for a secret code only, then leave your query the way it is now.

Check if regenerate_session_id() function actually works / Other security questions

I am building a website and i would like to secure it against Session Hijacking. Reading for this i came across someone saying that:
A general rule of thumb is to generate the session ID each time a user changes his access level.
1.When a user log in
2.When a user log out
3.When a user get administrative access
For what is worth, my website will be seperating the access levels into users logged-in and users logged-out. All forms are submitted using the POST method.
index.php
<?php
session_start();
//Setting the variable initialy to false
$_SESSION['LOGGED_IN'] = FALSE;
//to use SSL
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(isset($_POST['SUBMIT']))
{
if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])
{
//Open database connection
require_once('connect_db.php');
//Calling functions.php that includes all custom functions
//ErrorHandler()
require_once('functions.php');
$email = $_POST['EMAIL'];
$password = $_POST['PASSWORD'];
$statement = $DBH->prepare("SELECT * FROM user_details WHERE email=:email AND pwd=:password ");
$statement->bindParam(':email',$email);
$statement->bindParam(':password',$password);
$statement->setFetchMode(PDO::FETCH_ASSOC);
try{
$result = $statement->execute();
$rows = $statement->rowCount(); // shows how many times the user is available in the user_details table
$data = $statement->fetch(); //fetches the data related to that user from user_details table
}
catch(PDOException $e)
{
//this is custom function
echo ErrorHandler($e);
}
if($rows == 1)
{
//this means that the user has inserted the correct credentials
//regenerate session_id each time there is a change in the level of privilege to mitigate SESSION FIXATION
session_regenerate_id(true);
//turning logged in variable to true as soon as it finds a match
$_SESSION['LOGGED_IN'] = TRUE;
//saves the email into a session so it can be used in mainpage.php
$_SESSION['EMAIL'] = $email;
//redirect to main page
header('Location:https://www.example.com/mainpage.php');
}
else
{
echo "<br />Wrong username or password!<br />";
}
}//closing *if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])*
}//closing *if($_POST['SUBMIT'])*
//creating a random token to inject in our HTML form
$token = base64_encode(openssl_random_pseudo_bytes(32));
//store the random token in the session variable so we can later compare it to the one in the HTML form
$_SESSION['TOKEN'] = $token;
?>
<form action="index.php" method="POST" accept-charset="UTF-8">
<p>Email: <input type="email" name="EMAIL" /> </p>
<p><input type="hidden" name="TOKEN" value="<?php echo $token; ?>" /></p>
<p>Password <input type="password" name="PASSWORD" /> </p>
<p><input type="submit" name="SUBMIT" value="Submit" /></p>
</form>
The script accepts input email and password from the user,checks the database and if it finds a match it redirects the user to the mainpage.php.
mainpage.php
<?php
ob_start();
//the code to set the header must be called before output begins
session_start();
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(($_SESSION['LOGGED_IN'] == TRUE) && isset($_SESSION['LOGGED_IN']))
{
$email = $_SESSION['EMAIL'];
echo $email;
//Calling functions.php that includes all custom functions
//LogOut()
require_once('functions.php');
if(isset($_POST['LOGOUT']))
{
//its a custom function that is used for logging out
LogOut();
}
echo '
<form method="POST" action="mainpage.php">
<p><input type="submit" name="LOGOUT" value="Log Out" /></p>
</form>
';
}
else
{
echo "Please login in order to use example.com";
}
?>
Is there a way for me to check if the way i have built these 2 scripts really regenerate the Session ID? I am using Firefox's extension LIVE HTTP headers but i am not sure if i am reading it correctly.
Also, i cannot find a way to track down and read the content of COOKIES stored while using my browser (either Chrome or Firefox or even IE11). How can i do that?
Another question that is related with security:
Implementing an anti-CSRF token:
Do i need to implement an anti-CSRF token for each form in my website [i guess the answer is Yes but i want to confirm it]? Should each token be different than the token used in a previous form? For example the token in index.php to be different than the token used in mainpage.php if it had a form as well.
Does the token technique prevent against any other kind of attack?
I would be glad if you indicate wrong programming in the code above, so i can correct it and learn at the same time.
Thanks!
I'm going to focus on your questions and not necessarily a thorough code review, since I think your questions are the main reason you're posting.
A simple way to check your current session id or PHPSESSID is to check under Chrome's Developer Tools > Resources > Cookies. You'll see the (initially-generated) session ID. You can check this value before and after a user logs in. If the value changes, your session id has actually been regenerated.
You can also view cookies in Firefox by right-clicking the current page, going to View Page Info and using the Cookies tab.
On CSRF (prevention) tokens, the answer varies. People use different methods to go about them. I would say a majority of websites set a token in $_SESSION upon any regenerate of the session id. So for the duration of the current session, the CSRF token will remain the same and check against hidden inputs for that CSRF token.
On the other hand, I've also heard of regenerating a CSRF token for every single form that is client-facing. Your way of doing it is up to you. Nothing is 100% bulletproof, but getting as close to 100% as you can is the idea.
Take a few minutes to read up on CSRF tokens and the Synchronizer Token Pattern.
Best of luck!

AngularJS ngRoute and PHP $_SESSION variables

I have 3 pages:
index.php
login.php
display.php
index.php
Sets up AngularJS using the ngRoute module to navigate my pages.
login.php
Loaded by default and sets PHP $_SESSION variables.
display.php
Echos the contents of $_SESSION.
I navigate to display.php from login.php using a link setup with ngRoute.
Problem
display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.
I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.
Why is this?
I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:
<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">
That is not how it works. Your $_SESSION will never be available in your templates.
What you can do, is use an ajax request for your login authentication and have that request give you a session id.
Then use that session id when starting your session in further ajax requests (as already mentioned).
Then, when you want to store something to the php session, access the data via ajax request and php service.
a VERY, VERY, VERY, simple Example:
inside getFromSession.php
session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);
inside storeToSession.php
session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;
inside your login.php
$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
session_start();
echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling
inside anywhere in your angular where you need to access session data:
$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service
In general, no reason exists, why AngularJS apps, which request
PHP-based server-side stuff, won't be able to read $_SESSION.
That said, please provide at least the core concepts of of your AngularJS code, so we can provide further details.
Additionally, put just this in display.php:
<?
echo __FILE__
. '<br />' . date( DATE_RFC822 )
. '<br />' . var_dump( $_SESSION )
;
// intentionally skipped dangerous closing PHP-tag
Now run your AngularJS app and tell what comes out.
Make sure you start the session before reading the SESSION variables.
<?php
session_start();
echo $_SESSION["user9"];
?>
I don't think you're looking for angularJS.
I think you're looking for something more like this.
index.php:
<html>
<header>
<title>Login</title>
</header>
<body>
<form method="POST" action="login.php">
<input type="username" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
login.php
<?php
session_start();
if(empty($_POST)) {
die("You don't have permission to be here.");
} elseif(empty($_POST['username']) or empty($_POST['password'])) {
die("All fields are required.");
}
$username = "admin";
$password = "password";
if($_POST['password'] == $password && $_POST['username'] == $username) {
$_SESSION['loggedIn'] == "true";
header("Location: show.php");
} else {
die("Invalid login");
}
?>
show.php
<?php
if($_SESSION['loggedIn'] == "true") {
echo "You are logged in";
} else {
die("You don't have permission to be here.");
}
?>

User Getting Logged Out After Making First Comment

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.

Categories