Hi,
Im trying to add an else option to a page to show that someone is not logged in.
<?php
$query = mysql_query("SELECT * FROM users ORDER BY ID DESC LIMIT 1");
while($row = mysql_fetch_array($query)) {
if($query){
'<li>You are sucessfully logged in as <?php echo $row['id']; ?>.</li>' }
else($query){
'<li>You are currently not logged in.</li>'
}
}
?>
The following code works fine but Im trying to add the above else option. Can anyone please advise how I can make the else work.
<?php
$query = mysql_query("SELECT * FROM users ORDER BY ID DESC LIMIT 1");
while($row = mysql_fetch_array($query)){
?>
<li>You are sucessfully logged in as <?php echo $row['id']; ?>.</li>
<?php
}
?>
cpradio
September 17, 2012, 10:49pm
2
First of all, when expecting a single row, ditch the while loop, it is unnecessary.
Which then gives you the following:
<?php
$query = mysql_query("SELECT * FROM users ORDER BY ID DESC LIMIT 1");
if ($query && mysql_num_rows($query) === 1) // query was successful and returned 1 row
{
$row = mysql_fetch_array($query);
echo '<li>You are sucessfully logged in as ' . $row['id'] . '</li>';
} else {
echo '<li>You are currently not logged in.</li>';
}
?>
kduv
September 17, 2012, 11:17pm
3
And looking at your SQL, it looks like as long as there are any records in your DB at all, every user will be seen as “logged in”.
cpradio
September 17, 2012, 11:18pm
4
Okay, today is showing I didn’t get a lot of sleep over the past couple of nights, yet another obvious piece I missed. Very good catch @kduv ;
Hi, what does this mean sorry? It something I should be concerned about?
The code you code you provided works fine however it displays the id twice.
I am trying to replace the following “You are currently not logged in.” with the following code but this creates an error. How do I add divs into an area like this please?
<div class="headerlinkright">
<a href="/siteinfo/aboutus.php" rel="nofollow" class='bloglink' >About Us</a>
</div>
<div class="headerlinkright">
<a href="/blog/blog.php" rel="nofollow" class='bloglink' >Blog</a>
</div>
</div>
cpradio
September 19, 2012, 8:16pm
6
If you look at your SQL query, “SELECT * FROM users ORDER BY ID DESC LIMIT 1” you are not limiting it with a WHERE clause to check that the User is truly logged in, you are simply checking that at least 1 user exists in the table.
justlukeyou:
The code you code you provided works fine however it displays the id twice.
I am trying to replace the following “You are currently not logged in.” with the following code but this creates an error. How do I add divs into an area like this please?
<div class="headerlinkright">
<a href="/siteinfo/aboutus.php" rel="nofollow" class='bloglink' >About Us</a>
</div>
<div class="headerlinkright">
<a href="/blog/blog.php" rel="nofollow" class='bloglink' >Blog</a>
</div>
</div>
Can you paste your entire code so I can see it as a whole? It is hard to figure things out only seeing segments at a time.
Hi,
Should I be using this?
<?php
$query = 'SELECT * FROM users WHERE id = "' . mysql_real_escape_string($id) . '" LIMIT 1';
if ($query && mysql_num_rows($query) === 1) // query was successful and returned 1 row
{
$row = mysql_fetch_array($query);
echo '<li>You are sucessfully logged in as ' . $row['id'] . '</li>';
} else {
echo '<a href="/blog/blog.php" >Blog</a>';
}
?>
Damn no its not this because when I create two profiles and login with the first it gives me the ID number of the second profile!
This is all the code. The is that someone logs in and then goes the index page which displays their unique ID number (I will change this profile name)
Login Page
// Reset errors and success messages
$errors = array();
$success = array();
// Login attempt
if(isset($_POST['loginSubmit']) && $_POST['loginSubmit'] == 'true'){
$loginEmail = trim($_POST['email']);
$loginPassword = trim($_POST['password']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
if (!$email)
{
$error = 'Please enter your email address in a valid format. Example: bobsmith@companyname.com';
}
if(strlen($loginPassword) < 6 || strlen($loginPassword) > 12)
$errors['loginPassword'] = 'Your password must be between 6-12 characters.';
if(!$errors){
$query = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($loginEmail) . '" AND password = MD5("' . $loginPassword . '") LIMIT 1';
$result = mysql_query($query);
if(mysql_num_rows($result) == 1){
$user = mysql_fetch_assoc($result);
$query = 'UPDATE users SET session_id = "' . session_id() . '" WHERE id = ' . $user['id'] . ' LIMIT 1';
mysql_query($query);
header('Location: index.php');
exit;
}else{
$errors['login'] = 'No user was found with the details provided.';
}
}
}
// Register attempt
if(isset($_POST['registerSubmit']) && $_POST['registerSubmit'] == 'true'){
$registerEmail = trim($_POST['email']);
$registerPassword = trim($_POST['password']);
$registerConfirmPassword = trim($_POST['confirmPassword']);
if(strlen($registerPassword) < 6 || strlen($registerPassword) > 12)
$errors['registerPassword'] = 'Your password must be between 6-12 characters.';
if($password != $confirmPassword && !$error) {
$error = "The passwords you entered did not match.";
}
$emailAddress = filter_var($_POST['emailaddress'], FILTER_VALIDATE_EMAIL);
if (!$emailAddress)
{
$error = 'Please enter your email address in a valid format. Example: bobsmith@companyname.com';
}
if($registerPassword != $registerConfirmPassword)
$errors['registerConfirmPassword'] = 'Your passwords did not match.';
// Check to see if we have a user registered with this email address already
$query = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($registerEmail) . '" LIMIT 1';
$result = mysql_query($query);
if(mysql_num_rows($result) == 1)
$errors['registerEmail'] = 'This email address already exists.';
if(!$errors){
$query = 'INSERT INTO users SET email = "' . mysql_real_escape_string($registerEmail) . '",
password = MD5("' . mysql_real_escape_string($registerPassword) . '"),
date_registered = "' . date('Y-m-d H:i:s') . '"';
if(mysql_query($query)){
$success['register'] = 'Thank you for registering. You can now log in on the left.';
}else{
$errors['register'] = 'There was a problem registering you. Please check your details and try again.';
}
}
}
$query = mysql_query("SELECT id FROM users WHERE email = '".$email."' LIMIT 1");
if(mysql_num_rows($query) > 0 && !$error) {
$error = "Sorry, that email is already in use!";
}
print_r($website);
if(!$error) {
$query = mysql_query("INSERT INTO users (email) VALUES ('".$password."', '".$password."', '".mysql_real_escape_string(md5($password))."', '".$email."')");
if($query) {
$message = "Hello ".$_POST['email'].",\\r\
\\r\
Thanks for registering with EventVital.com! We hope you enjoy your stay.\\r\
\\r\
Many Thanks,\\r\
.com";
$headers = "From: ".$website['name']." <".$website['email'].">\\r\
";
mail($_POST['email'], "Welcome", $message, $headers);
setcookie("user", mysql_insert_id(), $time);
setcookie("pass", mysql_real_escape_string(md5($password)), $time);
header("Location: users.php");
} else {
$error = "There was a problem with the registration. Please try again.";
}
}
echo $_POST['email'];
echo $message;
echo $headers;
?>
Index
<?php
$query = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($email) . '" LIMIT 1';
if ($query && mysql_num_rows($query) === 1) // query was successful and returned 1 row
{
$row = mysql_fetch_array($query);
echo '<li>You are sucessfully logged in as ' . $row['id'] . '</li>';
} else {
echo '<a href="/blog/blog.php" >Blog</a>';
}
?>
Im trying to read it by the email address in the database to show the corresponding ID number. Can anyone advise how I can do this please?
cpradio
September 19, 2012, 11:49pm
11
It is on my to do list. I might not be able to get to it tonight, but I should be able to get to it tomorrow.
kduv
September 20, 2012, 1:36am
12
Try something like this …
Login Page:
<?php
session_start();
$_SESSION['userLoggedIn'] = 0;
$_SESSION['userEmail'] = '';
$_SESSION['userID'] = '';
// Reset errors and success messages
$errors = array();
$success = array();
// Login attempt
if(isset($_POST['loginSubmit']) && $_POST['loginSubmit'] == 'true')
{
$loginEmail = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$loginPassword = trim($_POST['password']);
if ($loginEmail === false)
{
$errors['loginEmail'] = 'Please enter your email address in a valid format. Example: bobsmith@companyname.com';
}
if(strlen($loginPassword) < 6 || strlen($loginPassword) > 12)
{
$errors['loginPassword'] = 'Your password must be between 6-12 characters.';
}
if(count($errors) === 0)
{
$query = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($loginEmail) . '" AND password = MD5("' . $loginPassword . '") LIMIT 1';
$result = mysql_query($query);
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result) === 1)
{
$row = mysql_fetch_assoc($result);
$_SESSION['userLoggedIn'] = 1;
$_SESSION['userEmail'] = $loginEmail;
$_SESSION['userID'] = $row['id'];
header('Location: index.php');
exit;
} else {
$errors['login'] = 'No user was found with the details provided.';
}
}
}
/*
The rest of your login page code
*/
And your index page:
<?php
session_start()
if ($_SESSION['userLoggedIn'])
{
echo '<li>You are sucessfully logged in as ' . $_SESSION['userEmail'] . ' (ID: '. $_SESSION['userID'] . ')</li>';
} else {
echo '<a href="/blog/blog.php" >Blog</a>';
}
?>
cpradio
September 20, 2012, 10:00am
13
Thanks @kduv ; for developing this further.
The only thing I would change, is to use mysql_real_escape_string() around $loginPassword too. Since it is being concatenated into the query, it is still susceptible to a SQL Injection attack.
Updated line:
$query = 'SELECT * FROM users WHERE email = "' . mysql_real_escape_string($loginEmail) . '" AND password = MD5("' . mysql_real_escape_string($loginPassword) . '") LIMIT 1';
This works brilliantly, one thing puzzles me though. When I delete the profile from the database and the refresh the index page it still shows as logged in.
Is it okay to do this?
cpradio
September 20, 2012, 9:04pm
15
With the way it is coded, it will do that up until the session expires. You can call session_stop() to kill the session when the user is deleted (if doing it programmatically). Or you can verify the session data on each page load by querying against your users table to verify the $_SESSION [ ‘userEmail’ ] the $_SESSION [ ‘userID’ ] are valid.
Sounds complicated! Im trying to think of every eventuality as Im completely new to registration scripts.
I’m trying to use this on the logout page but it no longer works. Should I be using this as the session
($_SESSION['userLoggedIn'])
$query = 'UPDATE users SET session_id = NULL WHERE id = ' . $_SESSION['user']['id'] . ' LIMIT 1';
mysql_query($query);
unset($_SESSION['user']);
header('Location: displaytest.php');
exit;
cpradio
September 20, 2012, 9:25pm
17
You will need to use unset on all session variables
unset($_SESSION['userLoggedIn']);
unset($_SESSION['userEmail']);
unset($_SESSION['userID'])
Your session_id column in the users table is never updated on login, so I don’t think setting that to null will do anything
That worked a treat.
You guys are bloody good at this.
kduv
September 21, 2012, 12:40am
19
You can also simply do:
$_SESSION = '';
It really all comes down to how you want to do it. There is no “one correct way”.