PHP Online users--- Sessions function - php

When a person logs in , the online column in the table is set to 1 , and when he logs out , it is set to 0 . I achieved the Login script , but problems on ending the session with SQL query .. Please do help !
There is No Error Displayed but Online value remains as 1 even after logging out
**LOGOUT SCRIPT**
<?php
$offline = $_SESSION["username"] ;
?>
<?php
//If the user is logged, we log him out
if(isset($offline))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
$con=mysqli_connect("localhost","root","","chat");
mysqli_query($con,"UPDATE users SET Online=0
WHERE username='.$offline.'");
mysqli_close($con);
?>
LOGIN SCRIPT
<?php
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
$con=mysqli_connect("localhost","root","","chat");
$sql = mysql_query('UPDATE users SET Online=1 where username="'.$username.'"');
?>
<div class="message">You have successfuly been logged. You can access to your member area.<br />
Home</div>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<form action="connexion.php" method="post">
Please type your IDs to log in:<br />
<div class="center">
<label for="username">Username</label><input type="text" name="username" id="username" value="<?php echo htmlentities($ousername, ENT_QUOTES, 'UTF-8'); ?>" /><br />
<label for="password">Password</label><input type="password" name="password" id="password" /><br />
<input type="submit" value="Log in" />
</div>
</form>
</div>
And , when I do the SQL query , How do I do the if Online = 1 , display online.png ? else 'Blank space ' ?
Thanks in advance !

The below code is for logout.php
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{echo $_SESSION['username'];
//We log him out by deleting the username and userid sessions
$username=$_SESSION['username'];
$sql="UPDATE users SET online=0 WHERE username='$username'";
mysql_query($sql);
unset($_SESSION['username'], $_SESSION['userid']);
?>
And this one for sign_up.php
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['username']))

use session_start();
ANd session_destroy(); FOR LOGOUT.

Related

Login page just loads the php script when logging in

Working on a website implementing login features for coursework. Currently have script files written but when i test it , it loads login.php which is what im using for the script.
<form action="login.php" method="post">
<div class="imgcontainer">
<img src="img/icons/avatar.png" alt="ELEAGUE" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" name="username" maxlength="40">
<label><b>Password</b></label>
<input type="password" name="pass" maxlength="50">
<button type="submit">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#fff">
<span class="psw">Forgot password?</span>
</div>
</form>
And the script is
<?php
//Connects to your Database
$conect = mysqli_connect("db location","username","password", "forks") or die(mysql_error());
//Checks if there is a login cookie
if(isset($_COOKIE['ID_your_site'])){ //if there is, it logs you in and directs you to the members page
$username = $_COOKIE['ID_your_site'];
$pass = $_COOKIE['Key_your_site'];
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysqli_fetch_array( $check )){
if ($pass != $info['password']){}
else{
header("Location: login.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) {
// makes sure they filled it in
if(!$_POST['username']){
die('You did not fill in a username.');
}
if(!$_POST['pass']){
die('You did not fill in a password.');
}
// checks it against the database
if (!get_magic_quotes_gpc()){
$_POST['email'] = addslashes($_POST['email']);
}
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysqli_num_rows($check);
if ($check2 == 0){
die('That user does not exist in our database.<br /><br />If you think this is wrong try again.');
}
while($info = mysqli_fetch_array( $check )){
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
die('Incorrect password, please try again.');
}
else{ // if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie(ID_your_site, $_POST['username'], $hour);
setcookie(Key_your_site, $_POST['pass'], $hour);
//then redirect them to the members area
header("Location: members.php");
}
}
}
else{
// if they are not logged in
?>
any help is appreciated, thanks

check if admin or not php

I have a database table that holds a users username, password and other information as well as whether theyre and administrator or not. Its currently set to Char where A is for admin and U is for normal user.
I have the following code which checks if a user exists:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$_SESSION['login_user']=$user;
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if(mysqli_num_rows($result) == 1) {
header("Location: home.php");
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
</html>
How would i check if Account_Type is A and if so direct the user to another page instead of the normal home.php page?
EDIT:
It works fine however the admin wont log in.
Ive given it test username of 456 and a password of 456 when i enter them into the two textboxes nothing happens, the screen just refreshes and im back on the login page:
new code below:
<?php
session_start(); // Starting Session
include_once('config.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['user']) || empty($_POST['pass'])) {
$error = "Please complete both fields";
}
else
{
// Define $username and $password
$user=$_POST['user'];
$pass=md5($_POST['pass']);
// To protect MySQL injection for Security purpose
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($mysqli, $user);
$pass = mysqli_real_escape_string($mysqli, $pass);
// SQL query to fetch information of registered users and finds user match.
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
//set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysqli_close($mysqli); // Closing mysqlinection
}
}
?>
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<title>Login</title>
</head>
<body>
<div id = "logReg">
<span href="#" class="button" id="toggle-login">Log in</span>
</div>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form action = "" id = "logregform" method = "POST">
<p id = "err"> <?php if(isset($error)) {echo $error;} ?> </p>
<input id = "logtxt" type="text" placeholder="Username" name = "user" required/>
<input type="password" placeholder="Password" name = "pass" required/>
<input type="submit" value="Log in" name = "submit" />
<br>
<br>
<p id ="bklg">Dont have an account? Sign up</p>
</form>
</div>
<script>
$('#toggle-login').click(function(){
$('#login').slideToggle('fast');
});
</script>
</html>
You are going about this the wrong way. Every page that requires the user to be authenticated should check at the very start if the user is authenticated and at what level. The way to do that is to use the session.
Right now you are setting the session variable before you even check whether the user / password combination is correct so you are effectively logging in anybody who enters a username.
You need to store the variables in the session only upon successful login and as mentioned you need to get a row from your result set to get the user information:
// Personally I would use a prepared statement here
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE Username='$user' AND Password='$pass'");
if ($row = mysqli_fetch_array($result)) {
// Now you can set the session variables
$_SESSION['Username'] = $row['Username'];
$_SESSION['Account_Type'] = $row['Account_Type'];
// Add any additional user information to the session that you might need later on
if ($row['Account_Type'] === 'A') {
header ("location: adminHome.php");
exit;
} else {
header ("location: home.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
Now in every page where a user is required you can do:
session_start();
if (isset($_SESSION['Username']))
{
// valid user, additional checks for user type?
}
else
{
// not a valid / logged in user
}
Note:
(unsalted...) md5 is unsafe to use for passwords, see Secure hash and salt for PHP passwords;
$row = mysqli_fetch_array($result);
if ($row['Account_Type'] === 'A') {
} elseif ($row['Account_Type'] === 'U') {
} else {
}

how to make multiuser?

firstly I get this coding from http://www.webestools.com/scripts_tutorials-code-source-15-personal-message-system-in-php-mysql-pm-system-private-message-discussion.html
before this I create user page and admin page using same coding. I edit same coding to see different user and admin page. I run at same browser at same time.. It run properly. But for this coding I make user and admin using same coding, same browser and run same time. I log in for admin first then log in for user. after I log in for user, I refresh admin page. session that I use in admin change to become like user page.
connexion.php
<?php
include('config.php');
?>
<div class="header">
<img src="<?php echo $design; ?>/images/logo.png" alt="Members Area" />
</div>
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
?>
<div class="message">You have successfuly been loged out.<br />
Home</div>
<?php
}
else
{
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
<div class="message">You have successfuly been logged. You can access to your member area.<br />
Home</div>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<form action="connexion.php" method="post"> Please type your IDs to log in:<br />
<div class="center">
<label for="username">Username</label><input type="text" name="username" id="username"value="<?
php echo htmlentities($ousername, ENT_QUOTES, 'UTF-8'); ?>" /><br />
<label for="password">Password</label><input type="password" name="password" id="password" />br />
<input type="submit" value="Log in" />
</div>
</form>
</div>
<?php
}
}
?>
index.php
<?php
include('config.php')
?>
<?php
//We display a welcome message, if the user is logged, we display it username
?>
Hello<?php if(isset($_SESSION['username'])){echo ' '.htmlentities($_SESSION['username'],ENT_QUOTES, 'UTF-8');} ?>,<br />
Welcome on our website.<br />
You can see the list of users.<br /><br />
<?php
//If the user is logged, we display links to edit his infos, to see his pms and to log out
if(isset($_SESSION['username']))
{
//We count the number of new messages the user has
$nb_new_pm = mysql_fetch_array(mysql_query('select count(*) as nb_new_pm from pm where ((user1="'.$_SESSION['userid'].'" and user1read="no") or (user2="'.$_SESSION['userid'].'" and user2read="no")) and id2="1"'));
//The number of new messages is in the variable $nb_new_pm
$nb_new_pm = $nb_new_pm['nb_new_pm'];
//We display the links
?>
Edit my personnal informations<br />
My personnal messages(<?php echo $nb_new_pm; ?> unread)<br />
Logout
<?php
}
else
{
//Otherwise, we display a link to log in and to Sign up
?>
Sign up<br />
Log in
<?php
}
?>
You have to Add to your session some new indexes for admin, it will be like the following
if a normal user logs in after checking if he's admin or not you store the normal user session indexes like these that you're using..
$_SESSION['username'] etc..
and if it's an admin logging in you store something like for example
$_SESSION['isAdmin'];
$_SESSION['adminName'];
etc..
and then you check for the Admin session in the admin panel..
and Then depending on the Session variables you decide what to show and what to not show, ask for login if there's no 'isAdmin' set..

Access Denied on Php Login

I have a buyer form, called "Buyer.php":
<form method="post" action="check_buyer.php" id="LoggingInBuyer">
<div style="width:265px;margin:0; padding:0; float:left;">
<label>Username: <span>Forgot Username?</span></label> <br />
<input id="UserReg" style="width:250px;" type="text" name="userName" tabindex="1" class="required" /></div>
<div style="width:265px;margin:0; padding:0; float:right;">
<label>Password: <span>Forgot Password?</span></label> <br />
<input id="UserReg" style="width:250px;" type="password" name="userPass" tabindex="2" class="required" /></div>
<div class="clearB"> </div>
<input type="submit" style="width:100px; margin:10px 200px;" id="UserRegSubmit" name="submit" value="Login" tabindex="3" />
</form>
A file called check_buyer.php (in the same dir):
<?php
session_start(); #recall session from index.php where user logged include()
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return false;
}
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
function validateUser($ifUserExists['uID'], $ifUserExists['uUserType']) {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $uID;
$_SESSION['uUserType'] = $uUserType; // 1 for buyer - 2 for merchant
}
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
// This is now throwing error of: Parse error: syntax error, unexpected '[', expecting ')' in on line 23 which is function validateUser($ifUserExists['uID'], $ifUserExists['uUserType']) {
and the file "index.php" in the buyer/ directory:
<?php
session_start();
if($_SESSION['uUserType']!=1)
{
die("You may not view this page. Access denied.");
}
function isLoggedIn()
{
return (isset($_SESSION['valid']) && $_SESSION['valid']);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
require_once('buyer_profile.php');
}else{
echo "<a href='../index.php'>Login</a>";
}
?>
The point of this is that when a username and password is entered, the user is logged in and directed to /buyer/index.php, to the buyer portion of that website. It seems everytime I login with the dummy credentials I made to test, it just blurts out : You may not view this page. Access denied. But, then if I go back by pressing back arrow in browser it has me logged in and showing a link to logout.
I did some trouble shooting:
1) Shown here, to test my sql query is fine and indeed it is. http://i.stack.imgur.com/n2b5z.png
2)Tried choing out echo 'the userid: ' . $userid; before it whines about You may not view.. and it doesn't print anything.
How do I go about getting this userID? I double checked the field names in the database and all is fine..
From a quick check, it looks like you're setting $_SESSION['uUserType'] = $userType in validateUser(), but don't seem to be passing in $userType itself to that function. So $_SESSION['uUserType'] won't be 1, but $_SESSION['valid'] will be, because you're setting it to that in validateUser().
I suspect you should be passing valid data in to validateUser in order to set it into the session.
e.g.
validateUser($ifUserExists['uID'], $ifUserExists['uUserType']);
function validateUser($uID, $uUserType) {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $uID;
$_SESSION['uUserType'] = $uUserType; // 1 for buyer - 2 for merchant
}

cant make login page work

I have this php page that posts to itself and then it checks weather if to login someone or not. The problem I am having is that if it logins... then it still shows the username and password textboxes.. but if i refresh they go away and now the welcome thing comes up thanks to the session.
What i want is to once the submit is clicked and it logs the person in to immediately not show the textboxes (username, password) and show the welcome message. Right now i have to refresh.
Please note i am new to PHP and any wise advise will be much appreciated.
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
?>
Problem here is just your code is not in sequence. I have corrected Try it now.
<?php
session_start();
echo "<body>";
//Start session
//print_r($_SESSION);exit;
//Check whether the session variable SESS_MEMBER_ID is present or not
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
if(isset($_POST))
{
$login_query = "SELECT reg_id, role_id, f_name FROM registration WHERE f_name = '$_POST[logInUsername]' AND password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("sunlinux","pukhraj","pukhraj123")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("testbaj", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["f_name"];
$userrole = $row["role"];
$userid = $row["reg_id"];
}
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
}
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
//Write session to disc
session_write_close();
echo "<form method=\"post\" ><div id=\"login\" class=\"login\">
<label for=\"login\">User Name</label>
<input type=\"text\" name=\"logInUsername\" />
<label for=\"Password\">Password</label>
<input type=\"password\" name=\"logInPassword\" />
<input type=\"submit\" value=\"Submit\" class=\"button\" />
</div>";
}
else
{
$sessionName = $_SESSION['SESS_NAME'];
echo "<div id=\"login\" class=\"login\">
<label for=\"welcome\">Welcome '$sessionName' !</label>
</div>";
}
?>
Small changes :
Just plase form tag at appropriate place.
Never mix code after post and before post.
here all database stuff should be execute after submit so I enclosed them in condition if(isset($_POST))
due to nonlinearity of code it was creating session after one more refresh after post data. Now corrected.
for message :
do below changes :
give name to submit button <input type=\"submit\" name=\"submit\" value=\"Submit\" class=\"button\" />
replace first if condition with if(isset($_POST['submit']))
So, not dealing with any of the security or style issues that are here...
Right now you are seeing if the session is set. If it is not, then you process the login. After processing the login, you display the form fields.
You should actually check for 3 states...
Is someone already logged in?
Do you need to process a login?
If neither of those, show normal form...
You can do this by using your existing isset for the session field.
Then if it is not set, check if the post fields are set... if they are set, process a login.
Otherwise, show the basic login form.
EDIT:
Full code sample (sorry for the terrible formatting, mostly cut and paste...:
<?php
echo "<form method=\"post\" action=\"index.php?form_type=$page_vals\">";
echo "<body>";
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) != '')) {
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else if ($_POST[logInPassword] != null && $_POST[logInUsername] != null)
{
extract($_POST);
$username = "";
$password = "";
$userrole = "";
$userid ="";
$login_query = "SELECT user_id, user_role, user_username FROM users WHERE user_username = '$_POST[logInUsername]' AND user_password = '$_POST[logInPassword]'";
if(!($database = mysql_connect("localhost","root","")))
die("<p>Could not connect to database</p></div></div>
</body>
</html>");
if(!mysql_select_db("mydatabase", $database))
die("<p>Could not open my databases database</p></div>
</div>
</body>
</html>");
if(!($result = mysql_query($login_query, $database)))
{
print("Could not execute query!<br/>");
die(mysql_error()."</div>
</div>
</body>
</html>");
}
if (mysql_num_rows($result) == 0) {
print("Please verify your login information<br/>");
}
while ($row = mysql_fetch_assoc($result)) {
$username = $row["user_username"];
$userrole = $row["user_role"];
$userid = $row["user_id"];
}
echo "Hello - '$username'";
mysql_close($database);
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $userid;
$_SESSION['SESS_NAME'] = $username;
//Write session to disc
session_write_close();
$sessionName = $_SESSION['SESS_NAME'];
echo '<div id="login" class="login">
<label for="welcome">Welcome '. $sessionName.'!</label>
</div>';
}
else
{
echo '<div id="login" class="login">
<label for="login">User Name</label>
<input type="text" name="logInUsername" />
<label for="Password">Password</label>
<input type="password" name="logInPassword" />
<input type="submit" value="Submit" class="button" />
</div>';
}
?>
Good luck!
Your logic just needs to be rethought. How about something like this? (pseduocode)
if( user is NOT logged in) // Check via session
{
$errors = array();
if( user submitted the form and is trying to log in) // Can be checked with a POST'd variable
{
// Set the session correctly here, query DB, etc.
// If there are any errors, add them to the $error array
}
if( !empty( $errors) || form was not submitted)
{
// Print the form and any errors (like invalid username / password combo)
}
exit; // Stop here
}
// Print welcome message here (since we know if we get here, the user is logged in)

Categories