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.
Related
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!
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.");
}
?>
Here is my login form. aka index.php
<form class="form-3" action="login.php?log=ok" method="post" >
<input type="text" name="username" id="login" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="submit" name="submit" value="Submit">
</form>
And here is my login checker. aka login.php
<?php
require_once 'classes/Personel.php';
$personel = new Personel();
$personel->setUsername($_POST['username']);
$personel->setPassword($_POST['password']);
$personel->login();
header("Location: index.php");
// REDIRECT
session_start();
if (strcasecmp($personel->getRole(), "LTO") == 0 ) {
$_SESSION['role'] = "LTO";
$_SESSION['personel'] = $personel;
header("Location: LTO");
}else if(strcasecmp($personel->getRole(), "LTFRB") == 0){
$_SESSION['role'] = "LTFRB";
$_SESSION['personel'] = $personel;
header("Location: LTFRB");
}else if(strcasecmp($personel->getRole(), "LGU") == 0){
$_SESSION['role'] = "LGU";
$_SESSION['personel'] = $personel;
header("Location: LGU");
}else if(strcasecmp($personel->getRole(), "ADMIN") == 0){
$_SESSION['role'] = "ADMIN";
$_SESSION['personel'] = $personel;
header("Location: admin");
}
?>
now when i try to access any accounts from them i can easily open its index page and other pages even i'am not login. How can i prohibit that? and how can i avoid the url rewriting?
eg. the index page of admin
try to open my link the correct account is admin-admin also try a wrong one..
Big Thanks in advance.
First thing, you need to set the redirect to index.php in proper place, with some condition.
I get your problem, but are you checking the session on each and everypage?
You need to implement a check at the beginning of each page that whether the session is properly set or not. Else redirect back to index.php.
You need to implement this code before each of your pages:
session_start();
if(isset($_SESSION['role'])){
if($_SESSION['role'] != "ADMIN") { //change the "ADMIN" to your unique role per page
echo "Access denied";
exit();
}
else {
header("Location: index.php");
}
You are calling header("Location: index.php") without any condition.
That means that you are always redirecting to index.php.
Any call to login.php will result in automatic redirect to index.php.
I don't know what $personel->login() exactly does but your code should look something like:
$authorized = $personel->login();
if (!$authorized) {
header("Location: index.php");
exit();
}
Also - session_start() should be at the top of the code.
Hope this helps!
You can place a check at the top of every page, and if user not logged in redirect them to an appropriate page, for example a login page.
Here's one approach to doing this.
When you login, set a $_SESSION variable (something like user_id), like this:
//If successful login:
$_SESSION['user_id'] = $userid_from_the_db;
Note that when using sessions, you must place session_start(); at the very TOP of each page.
Then, you can check if the user is logged in before displaying any page data.
Something like:
<?php
protect_page();
Where protect page can look like this:
if (isset($_SESSION['user_id'])===false) {
echo '<p>Please log in first</p>';
echo '<meta HTTP-EQUIV="REFRESH" content="5; url=login.php">';
}
Consider viewing this (free) tutorial from phpAcademy:
Registration and Login - Procedural version
Registration and Login - OOP version
Notes:
You can use either of these methods to redirect the page:
header("Location: pagename.php");
This is the preferred way, however you cannot output any other headers before using this command or it will fail.
<meta HTTP-EQUIV="REFRESH" content="5; url=pagename.php">
As a work-around, you can use this method to redirect the page, and the bonus is that it will wait the specified number of seconds before doing so (5 in this case, or zero if you choose).
I have begun developing this very simple PHP login that asks for a password to allow access to a website. It also creates a cookie to allow continued access until the user closes their browser window.
At the top of each page I check for the cookie:
<?php
if(!isset($_COOKIE['authorised']) || ($_COOKIE['authorised'] != 'true'))
{
include('login.php'); exit;
}
?>
If they don't then I exit and show a login form:
<?php
function pageURL()
{
$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;
}
$pageRedirect = pageURL();
if(isset($_POST['password']) && ($_POST['password'] == 'qwe123'))
{
setcookie('authorised', 'true'); header("Location:$pageRedirect",303);
}
else
{
include('noaccess.php'); exit;
}
?>
<form action="<?php echo pageURL(); ?>" method="post">
<input type="password" name="password" />
<input type="submit" title="I agree" value="I agree" name="submit" />
</form>
The current PHP is from an old Warning page when you had to agree to access the site, I want to modify it to work with a simple form so that if the user types a password say for example 'qwe123' then they create the cookie and then are redirected back to the page but now have access because of the cookie. If they get it wrong then another page is included and exited.
Can someone help me with this? Thanks
Please don't try to store things like "authenticated" in a client side cookie; that's incredibly insecure. A user can modify anything in a cookie - so in this case, I could look up the cookie in my browser settings and then edit it to set "authenticated" to true. I would then be logged in, without a username or password.
Have a look at PHP's session management functions. You should create a session and store any secure information server side, not client side.
An example using sessions would be the following;
<?php
session_start();
$secretpassword = 'qwert1234';
$secretusername = 'foobar';
if ($_SESSION['authenticated'] == true) {
// Go somewhere secure
header('Location: secure.php');
} else {
$error = null;
if (!empty($_POST)) {
$username = empty($_POST['username']) ? null : $_POST['username'];
$password = empty($_POST['password']) ? null : $_POST['password'];
if ($username == $secretusername && $password == $secretpassword) {
$_SESSION['authenticated'] = true;
// Redirect to your secure location
header('Location: secure.php');
return;
} else {
$error = 'Incorrect username or password';
}
}
// Create a login form or something
echo $error;
?>
<form action="login.php"><input type="text" name="username" /><input type="text" name="password" /><input type="submit" value="login" /></form>
<?php
}
It's a pretty ugly example, but this covers the meat of it
if the user is logged in already, do the secure stuff (of course, the secure.php script should also verify that the user is logged in)
if the user is not logged in, but they have submitted a form, check their details
if username/password incorrect, set an error messagee
if username/password correct, send them to secure place
display the error message, if set
display a login form
You run session_start() before sending any other output; this stores a session cookie on the client side, which only stores an identification number on the client side. All other data is stored on the server side, so it cannot be modified by the user.
There are several parameters that you can set on this to improve security, including httponly (prevents the cookie from being accessed via javascript, helps against XSS attacks) and secure (only transfer the cookie over SSL). These should be enabled if possible.
Just have the form submit to the page where you check the password, and it should work just fine.
However, you might have to change the $_SERVER["REQUEST_URI"]; to a more specific page, as this will simply be the page you are currently at (the page the form submitted to).
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.