Here is the code
I dont know whats wrong with it.
<?php
//Logout code
//Starting Session
session_start();
//Include
include ("includes/mass.php");
//Check if the user is logged in
$username = $_SESSION['username'];
$logged_in_query = "SELECT * FROM user WHERE loggedin='1' AND username='$username'";
$check_if_logged_in = mysql_query($logged_in_query);
if (isset($username))
{ while ($row = mysql_fetch_array($check_if_logged_in))
{
$logged_in = $row['loggedin'];
if ($logged_in == 1)
{
//User becomes logged out on database records
$sql_logout = "UPDATE user SET loggedin='0' WHERE loggedin='1' AND username='$username'";
$logout_query = mysql_query($logout_query);
//Logout page
session_destroy();
echo "You have been logged out.","<br>"."<a href='index.php'>Click Here To Go Back</a>";
}
}
} else
{
echo"You are not logged in"."<br><a href='register.php'>Click To Sign Up</a>";
}
?>
Do you have a mysql link object (from mysql_connect() / mysql_select_db() ?) From your comments below, it doesn't sound that way.
This SQL is wrong:
$sql_logout = "UPDATE user WHERE loggedin='1' AND username='$username'";
Should be:
$sql_logout = "UPDATE user SET loggedin=0 WHERE loggedin='1' AND username='$username'";
?
You probably also mean to be using mysql_fetch_assoc() instead of mysql_fetch_array().
This line:
$logout_query = mysql_query($logout_query);
Should be
$logout_query = mysql_query($sql_logout);
Put in your correct mysql connection and db information and try to run this. Please post the output.
<?php
//Logout code
//Starting Session
session_start();
echo "hello<br />";
//Include
include ("includes/mass.php");
echo "no problem in mass.php!<br />";
// FILL ME IN
$my_link = mysql_connect($server, $username, $password, TRUE);
mysql_select_db('your_db', $link);
//Check if the user is logged in
$username = $_SESSION['username'];
$logged_in_query = "SELECT loggedin FROM user WHERE loggedin='1' AND username='$username'";
echo $logged_in_query . "<br />";
$check_if_logged_in = mysql_query($logged_in_query, $my_link);
var_dump(mysql_num_rows($check_if_logged_in));
if (isset($username))
{
while ($row = mysql_fetch_assoc($check_if_logged_in))
{
var_dump($row);
$logged_in = $row['loggedin'];
if ($logged_in == 1)
{
//User become logged out on database records
$sql_logout = "UPDATE user SET loggedin=0 WHERE loggedin='1' AND username='$username'";
$logout_query = mysql_query($sql_logout, $my_link);
//Logout page
session_destroy();
echo "You have been logged out.","<br>"."<a href='index.php'>Click Here To Go Back</a>";
}
else
{
echo"You are not logged in"."<br><a href='register.php'>Click To Sign Up</a>";
}
}
}
?>
what you have written is very bad code. i would suggest you do like this
1. create a session in the login page once their username and password matches with the entry in the db
2. destroy that session when they say log out.
your implementation of checking the user using db is not scalable. everytime it gets executed and its not the right idea of doing it.
I would use something like this:
<?php
//Logout code
//Starting Session
session_start();
//Include
include ("includes/mass.php");
//Check if the user is logged in
$username = $_SESSION['username'];
if (isset($username))
{
$logged_in_query = "SELECT * FROM user WHERE loggedin='1' AND username='".$username."' LIMIT 1";
$check_if_logged_in = mysql_query($logged_in_query);
$logged_in = mysql_fetch_field($check_if_logged_in);
if ($logged_in == 1)
{
//User becomes logged out on database records
$sql_logout = "UPDATE user SET loggedin='0' WHERE loggedin='1' AND username='".$username."' LIMIT 1";
$logout_query = mysql_query($logout_query);
if ($logout_query)
{
//Logout page
session_destroy();
echo "You have been logged out.","<br>"."<a href='index.php'>Click Here To Go Back</a>";
}
else
{
//Couldn't update the user table to set your login status.
echo "MYSQL Error, please contact admin LO-2";
exit();
}
}
else
{
echo "You are not logged in"."<br><a href='register.php'>Click To Sign Up</a>";
}
}
else
{
echo "You are not logged in"."<br><a href='register.php'>Click To Sign Up</a>";
}
?>
Not tested
Max
Related
I'm fairly new to PHP and have hit a brick wall. When a user logs in on my site, a session ID is generated and stored in a database, along with the expiration time, user's email and IP. The session ID is also stored in the user's cookies, and expires after 30 minutes of inactivity. When a page is loaded, part of the navbar is determined by whether or not they are logged in, which is determined by whether or not part a cookie is set. My code is shown below.
Change the navbar
<?php
if (isset($_COOKIE['sessionID'])) {
echo "<li><i class=\"material-icons\">account_circle</i></li>";
} else {
echo "<li>Login</li>\n";
}
?>
Log a user in
$sql = "SELECT * FROM users WHERE `email`='$email'";
$query = mysqli_query($conn, $sql);
if (password_verify($password, mysqli_fetch_assoc($query)['password'])) {
$sessionID = uniqid('id_', true);
$sql = "INSERT INTO sessions (`email`, `ID`, `expiration`, `ip`) VALUES ('$email', '$sessionID', '" . date("Y-m-d H:i:s", strtotime("+30 minutes")) . "', '" . $_SERVER['REMOTE_ADDR'] . "')";
setcookie("sessionID", $sessionID);
$_COOKIE['sessionID'] = $sessionID;
mysqli_query($conn, $sql);
header("Location: https://[censor]/");
exit();
} else {
header("Location: https://[censor]/login?success=false");
exit();
}
I know a user has been logged in, at least to a degree, because sessionID shows up on the database and my cookies.
Update
I started using PHP sessions, and after getting them to work once, they appear to have stopped working. My new code is below.
Logging a user in
$sql = "SELECT * FROM users WHERE `email`='$email'";
$query = mysqli_query($conn, $sql);
if (password_verify($password, mysqli_fetch_assoc($query)['password'])) {
$_SESSION['email'] = $email;
header("Location: https://[censor]/");
echo $_SESSION['email'];
exit();
} else {
header("Location: https://[censor]/login?success=false");
exit();
}
And no, I did not forget to start a session, it is started at the very beginning of the file.
Example
<?php
if (isset($_SESSION['email']))
echo "<li><i class=\"material-icons\">account_circle</i></li>";
else
echo "<li>Login</li>\n";
?>
I had the same isset error. I don't know exactly why this is not working but I solved the problem with this:
$val = true;
if(isset($_COOKIE['sessionID'])){
$val = false;
}
if($val == true){
//action 1
}
else{
//action 2
}
I think that should work in your case as well. Or is isset generally not working, if you use it without the else?
it will be better if you use SESSIONS for login; here is a sample code.Here i get the login information from the login form, assign it to respective variables and compare with what is in my DATABASE.`
<?php session_start();
if (isset($_POST['submit'])) {
$username=$_POST['username'];
$password=$_POST['password'];
$username=validate_data($username);
$query="SELECT * FROM users;";
$result=mysqli_query($connection,$query);
comfirm_query($result);
//fetching login info
while ($user=mysqli_fetch_assoc($result)) {
//verifying info
if($user['username']==$username){
if (password_verify($password,$user['password'])) {
/*if success set the session super global variable with indexes
user_id and username with the values gotten from the database*/
$_SESSION['user_id']=$user['id'];
$_SESSION['username']=$username;
redirect_to("admin.php");
}
else{
$_SESSION['login_message']="username or password not correct";
}
}
else
$_SESSION['login_message']="username or password not correct";
}
}
?>
Now to verify login on any page which requires a user to be logged on
<?php
if(!isset($_SESSION['user_id'])){
header("location:login.php");
exit;
}else{
/*continue executing code on page; the else is not really
necessary as if the variable is not set, the user
will be redirected; but if it #is set ,
the just skip (permit me to use this word)
the if and get on with the code*/
}
?>
I'm trying to display username (cocname), but nothing happened. Do you see why? there is no error but the username is missing also and "Hello" is not displayed.Thank you.
<?php
session_start();
include_once 'config.php';
$prepend = "<span class='cocname'>";
$append = "</span>";
if (!isset($_SESSION['email'])) {
header("Location: signin.php");
}
$query = "SELECT cocname FROM users WHERE email=".$_SESSION['email'];
$result = $connect->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
{
echo $prepend."Hello ".$row['cocname'].$append;
}
}
?>
Well you need to use sessions here. For all the pages where you need login to work. Add this statement.
session_start();
Now, add session_start(); as the first line of your login page. Update your login page as below.
if ($result->num_rows > 0)
{
//user logged in
$_SESSION['logged'] =1;
$_SESSION['email']=$user;
//now since this would only return 1 result, you don't need to use a white loop.
$user_details = $result->fetch_assoc();
}
Read more :- http://www.w3schools.com/php/php_sessions.asp
Try this
Do write this in signing.php
$query = "SELECT email, password FROM users WHERE email ='$user' and
password='$pass'" ;
$result = $connect->query($query);
if ($result->num_rows == 0) {
header('Location: signin.php?failed=1');
}
if ($result->num_rows > 0) {
//Email and password matched
$_SESSION['logged_in'] = true;
$_SESSION['User'] = $result->fetch_assoc();
}
And in main.php check if user is logged in or not as
if($_SESSION['logged_in']){
echo "Successfully logged in";
}else{
echo "Login first to view this page";
}
Don't forget to start session on the top of page. And use $_SESSION["User"] to show user info on main page.
Update :
You should submit your form on the "signin.php" itself. If the user is successfully logged in, save a session like $_SESSION["is_login"] = true; and another session containing user info and redirect to the main.php. In the main.php check if "is_login" session is set and is true. If true user is logged in and show there user info from info session. If "is_login" session is not set redirect the user to "signin.php" to signin again.
Update 2
The only solution i found for you is
replace
$query = "SELECT cocname FROM users WHERE email=".$_SESSION['email'];
with
$email = $_SESSION['email'];
$query = "SELECT cocname FROM users WHERE email='$email'";
Update 3
Replace
$query = "SELECT cocname FROM users WHERE email=".$_SESSION['email'];
With
$query = "SELECT cocname FROM users WHERE email='{$_SESSION['email']}'";
I have started a session on config page, then $_SESSION['logged_out'] = 1; and on index page that:
if(isset($_SESSION['logged_out']))
{
echo "You have been logged out !";
unset($_SESSION['logged_out']);
}
But the echo not workig, like unset is before him. And i don`t understand why, please help me.
EDITED:
Config page:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connection.php';
include 'functions.php';
$logged_in = 0;
if(isset($_SESSION['username']) && isset($_SESSION['password']))
{
$username = sec($link, $_SESSION['username']);
$password = sec($link, $_SESSION['password']);
$udata = get_row($link, "SELECT * FROM accounts WHERE Username= '$username' && Password= MD5('$password')");
if(isset($udata['ID']))
{
$logged_in = 1;
if(isset($_GET['logout']))
{
unset($_SESSION['username']);
unset($_SESSION['password']);
$_SESSION['logged_out'] = "1";
mysqli_query($link, "UPDATE accounts SET rpgon = '0' WHERE Username = '$username'");
header('location: index.php');
}
}
} ?>
Index page:
if(isset($_SESSION['logged_out']))
{
echo "You have been logged out !";
unset($_SESSION['logged_out']);
}?>
This is it ...
If echo doesn't show anything is because the if condition is evaluated to false. This mean that $_SESSION['logged_out'] isn't set.
You have to start_session() on every page that uses the $_SESSION. In fact if you are using $_SESSION anywhere in your site, its best to start it on all your pages.
So add start_session() just after the first <?php to ensure it is always started for all pages
<php
start_session();
. . .
if(isset($_SESSION['logged_out']))
{
echo "You have been logged out !";
unset($_SESSION['logged_out']);
}
Added after additional info given
I think this may be one of your problems
$udata = get_row($link,
"SELECT * FROM accounts
WHERE Username= '$username'
&& Password= MD5('$password')"
);
The && should be AND, then this query should return a result. You should really be checking the result status from all query command like so:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start();
ob_start();
include 'connection.php';
include 'functions.php';
$logged_in = 0;
if(isset($_SESSION['username']) && isset($_SESSION['password']))
{
$username = sec($link, $_SESSION['username']);
$password = sec($link, $_SESSION['password']);
$udata = get_row($link, "SELECT * FROM accounts
WHERE Username= '$username'
AND Password= MD5('$password')"
);
// this would have shown the error in the sql query
// if it had been here before
if ( ! $udate ) {
echo mysqli_error($link);
exit;
}
// now this if will be executed
// although this if is probably no longer required
if(isset($udata['ID']))
{
$logged_in = 1;
if(isset($_GET['logout']))
{
unset($_SESSION['username']);
unset($_SESSION['password']);
$_SESSION['logged_out'] = "1";
mysqli_query($link, "UPDATE accounts SET rpgon = '0' WHERE Username = '$username'");
header('location: index.php');
// you should also follow a header() call with an exit;
exit;
}
}
}
?>
i trying to verify the username and password in the data before allowing the user entry. this is my code. the results is that it skips and goes to the else statement
if(!empty($_POST['username']) && !empty($_POST['code']))
{
$checkcode = mysql_query("SELECT * FROM members WHERE Username = '".$username."' AND Code = '".$code."'");
if(mysql_num_rows($checkcode) == 1)
// $row = mysql_fetch_array($checkcode);
{
header("Location: home.php");
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
Fix your formatting :)
I don't see you assigning $_POST['username'] to $username variable, same with $code.
I am creating a login system for my website. I want to grab the user's userID (aka a primary key out of the database) to use when they log in.
I have 3 files I'm using:
/index.php - that is basically the login form with a username and password fields. It contains this php code:
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
Once form is submitted, it goes to check_buyer.php (/check_buyer.php)
<?php
session_start(); #recall session from index.php where user logged
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';";
$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);
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 true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
echo 'sessuID: '.$_SESSION['uID'];
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$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();
}
?>
If the credentials are valid, the user is sent to login_new/buyer/index.php
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
The problem is, when I login with valid credentials it sends me to login_new/buyer/index.php with the account, but is not outputting the buyer ID using the code echo 'buyerid: '.$_SESSION['uID']; what am I doing wrong here?
Try commenting the header() redirect and echo the $_SESSION['uID'] right after you set it in function validateUser() to see if the session data is actually set right there