I have a problem with my logout script. It works fine, if a user presses logout it kills the session and goes to logout.php where the user is told they've been logged out.
But when the browser cache is emptied or if the site should not be connected to the internet and if a user clicks the logout button it comes up with this error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
It fails beacause it cant set logout to '1' so i want to know how i might go about putting an else statement in somewhere to say redirect to logout.php so i don't get that horrible syntax error message.
Here's my code:
<?php
ob_start();
require('includes/_config/connection.php');
require('includes/functions.php');
?>
<?php
session_start();
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']."")
or die(mysql_error());
?>
<?php
// Four steps to closing a session
// (i.e. logging out)
// 1. Find the session
// 2. Unset all the session variables
$_SESSION = array();
// 3. Destroy the session cookie
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Destroy the session
session_destroy();
redirect_to("login.php?logout=1");
ob_end_flush()
?>
You have double quotes and you should be using single quotes
Change this:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']."")
To:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id='" . $_SESSION['user_id'] . "'")
PLEASE NOTE You should replace all your mysql_* functions. As of PHP 5.5.0 they are deprecated. Use something like PDO or MySQLi
Yes, there is something wrong with your quotes: As long as the user_id is an integer value you could do it like this:
$result = mysql_query("UPDATE ptb_users SET user_online='Offline' WHERE id=".$_SESSION['user_id']);
In case it is a string, switch to single quotes:
$result = mysql_query('UPDATE ptb_users SET user_online="Offline" WHERE id="'.$_SESSION['user_id'].'"');
You can't call session_start() after output is sent- are your requires outputting anything?
Also ensure that $_SESSION['user_id'] actually has a value; print_r($_SESSION)
Related
I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>
I have created a user authentication system with necessary DB tables and php.
THe first time before I login (Before any SESSION is created) the redirect on every page works perfect (ie Redirects to the login page if not logged in).
But once I login with a user and then logout the same doesnt work. I think it might be a problem with not ending the SESSION (Sorry if am wrong)
Here are some pieces of the code in each Page
Login PHP
<?php
session_start();
$message="";
if(count($_POST)>0)
{
include('config.php');
echo $_POST['username'];
$result = mysql_query("SELECT * FROM members WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["id"] = $row[ID];
$_SESSION["username"] = $row[username];
$_SESSION["password"] = $row[password];
$_SESSION["mname"] = $row[mname];
$_SESSION["fname"] = $row[fname];
date_default_timezone_set("Asia/Calcutta");
$lastlog=date("d/m/Y");
$logtime=date("h:i a");
$query = "UPDATE `members` SET `lastlogin`='$lastlog',`logintime`='$logtime' WHERE `ID`='$row[ID]'";
mysql_query($query);
$_SESSION['logged'] = TRUE;
}
else
{
echo "<SCRIPT>
alert('Wrong Username/Password or Awaiting Approval');
</SCRIPT>";
header("Location:login_failed.html");
}
}
if(isset($_SESSION["id"])) {
header("Location:member/myprofile.php");
}
?>
PHP code on every page
<?php
session_start();
include('config.php');
if(!$_SESSION['logged'])
{
header("Location: ../login.html");
exit;
} ?>
And Finally Logout
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["mname"]);
unset($_SESSION["fname"]);
header("Location:../login.html");
?>
Is there any problem with my Code. Am i missing something? I couldn't get it right. Pls Help
Thanks guys got it solved..
Now can you tell me How I can redirect login.php to user home page(myprofile.php) in case the User is logged in (Session exists) - Like facebook,gmail etc
Instead of calling unset() on each session var, you can simply use session_destroy(), which will destroy all of the current session data.
session_start();
session_destroy();
header("Location:../login.html");
For complete destructive power, you might also want to kill the session cookie:
setcookie(session_name(), '', 1);
See this question for a more complete example of session logout.
You need to unset $_SESSION['logged']
Also you should reference keys in the $row variable with strings. Eg $row['username'];.
Turning on E_NOTICE level warnings with error_reporting will help you with this.
If you haven't already, reset the session login
unset($_SESSION['logged']);
Or just change it to false
$_SESSION['logged'] = false;
When you are directly hitting a page in address bar for the first time then its a new request which goes to the server and server checks for existing session as written in your code. But its not same when you are pressing back button after logout. In this case there is no request is going to the server instead the request is fetched from browser cache. If you want to disable this situation then you have to tell browser explicitly to not to store your page in cache memory. For more detail please go through this link
I'm getting an error using session_destroy() in my PHP code.
The following script is on every page and if a user is signed in, it checks if the session is valid or not, killing the session if it's not.
session_start();
// check for users already signed in and check session
if (isset($_SESSION['user_id'])) {
$uid = $_SESSION['user_id'];
// check user_id is a valid id
if (!is_numeric($uid) || $uid < 0) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
// if user agent is different, kill session
if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
// if user's last login record fails to match session_id, kill session
$SQL = "SELECT user_session FROM users_logins ";
$SQL .= "WHERE user_id = :user_id ";
$SQL .= "ORDER BY time_in DESC LIMIT 1;";
$STH = $DBH_P->prepare($SQL);
$STH->bindParam(':user_id', $uid);
$STH->execute();
$row = $STH->fetch();
if ($STH->rowCount() > 0) {
$db_sid = $row['user_session'];
}
if ($db_sid !== session_id()) {
session_unset();
session_destroy();
session_regenerate_id(true);
}
}
The error I receive indicates the failure is coming from the last session_destroy() call.
Am I using session_destroy() correctly or not? I have read other questions on here but most answers advise that session_start() must be used before destroying it, but I have started the session at the top, before the check begins.
You do some crazy stuff there (but you need to negotiate that with your own, I don't cover it in my answer), the reason why you see the error message is quite simple:
session_regenerate_id(true);
is commanding PHP to destroy the old session. Problem is, you already did that, one line earlier:
session_destroy();
session_regenerate_id(true);
So just take a view from above. There is no reason in an OCD manner to throw as many functions as you see fit (but actually don't understand/know well) onto your session processing. Instead take the one function that is intended to do the job and actually process it's return value if you want to put some safety net in there actually. That would be more helpful.
I started creating a login system which utilised cookies for a "remember me" feature. All is working fine however I am having trouble deleting the cookie upon user logout.
If a user does not check the "remember me" box and logs in successfully I.e. does not create the cookie, the logout function works as expected and loads the login box.
If they don't do the latter and the user clicks the logout button the cookie remains and it shows they are still logged in.
If someone could shine some light as to why the cookie wont delete I would be very grateful.
Below is the code I am using:
PHP code that runs after a user tries to log in:
// If the form has been submitted
if(isset($_POST['login'])):
// Protect from unwanted code/string context
$username = strip_tags(addslashes(trim($_POST['username'])));
$string = strip_tags(addslashes(trim($_POST['password'])));
$remember = strip_tags(addslashes(trim($_POST['remember'])));
// Pass the returned variables from functions to a local versions
$password = salting($string); // Salt Password Preperation
$link = db_connect(); // DB connection
// Connect to the database and try to find a login match
$result = mysqli_query($link,"SELECT * FROM web_users WHERE username='".$username."' AND password='".$password."'");
$row = mysqli_fetch_object($result);
// Create erronous results if submitted data is invalid
if (mysqli_num_rows($result) !== 1):
$errmsg[0] = "Invalid Username or Password, please re-try";
endif;
$e_login = serialize($errmsg);
// If validation passes then continue
if (!$errmsg):
// Increment the login_count field by 1
$row->login_count++;
$count = $row->login_count;
// Retrieve the date for admin purposes
$date = date('Y-m-d-h:i:s'); // Y=year (4 digits) m=month (leading zero) h=hour i=minutes s=seconds
// Salt Password Preperation
$string = session_id();
$login_id = salting($string);
// Connect to the database and update the related row
$update = mysqli_query($link,"UPDATE web_users
SET login_count='".$count."',
login_last='".$date."',
login_id='".$login_id."',
logged='1'
WHERE id='".$row->id."'")
or die(mysqli_error($link));
// Create a multi-dimensional session array
$_SESSION['login'] = array('user' => $row->display_name,
'id' => $row->id,
'user_level' => $row->user_level);
if($remember == 1):
setcookie("login_user",session_id(),time() + (86400*7)); // 604800 = 1 week
endif;
// Free the memory and close the connection
mysqli_free_result($result);
mysqli_close($link);
// Take the user to the successive page if no errors
header("location: /");
endif;
endif;
HTML code to create the logout element:
<a href="/logout" title="Logout">
<img src="<? echo ASSETS . IMAGES . ICONS . GENERAL; ?>logout.png" alt="User Logout">
</a>
PHP code that runs when a user logs out:
function logout() {
// Load the db connect function to pass the link var
$link = db_connect();
if(is_array($_SESSION['login'])):
// Update the logged field to show user as logged out
$update = mysqli_query($link,"UPDATE web_users SET logged='0' WHERE id='".$_SESSION['login']['id']."'") or die(mysqli_error($link));
// Free the memory and close the connection
mysqli_free_result($update);
mysqli_close($link);
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if(isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time()-7000000, '/');
endif;
// Finally, destroy the session.
session_destroy();
// Take the user to the successive page if no errors
header("location: /");
endif;
}
The user, when logged in with the remember me checkbox to your site, will have two cookies. The session cookie, by default PHPSESSID, and the remember me cookie, login_user. In order to remove the session, you just remove the sesion cookie with this code:
if(isset($_COOKIE[session_name()])):
setcookie(session_name(), '', time()-7000000, '/');
endif;
The issue is that, aside from that, you need to unset the remember me cookie, with the following code.
if(isset($_COOKIE['login_user'])):
setcookie('login_user', '', time()-7000000, '/');
endif;
I would hazard a guess that your code
if(isset($_COOKIE[session_name()])):
setcookie(session_name(),'',time()-7000000,'/');
endif;
is your problem. Most likely the isset is returning false. I would remove it from the if statement if possible.
Also in addition as mentioned below in the comments. Did you use session_start()? There is no reference to it in your code above. This would cause session_name() to return empty.
To delete a cookie, you should set the expiration date in the past:
setcookie('login_user', '',time() - 3600);
You have this rule, but explicitly add the path parameter, although you have NOT used the path when setting the cookie, this might be the problem.
<?php
include 'connect.php';
include 'header.php';
$page = "signup.php";
// receive the invite code:
$code = $_POST['code'];
$sql = "SELECT codes FROM invites WHERE codes='$code'";
// check the table for matching codes
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) {
// end any previously defined sessions.
session_start();session_unset();session_destroy();
// start a new session
session_start();
// define the session variable.
// this allows us to check if it's set later and is required for
// the script to run properly.
$code = $_POST["code"];
mysql_query("DELETE FROM invites WHERE codes='$code'");
header('Location: '.$page);
exit;
} else {
echo "Invite invalid. Please try again later.";
echo $code;
}
include 'footer.php';
?>
I am trying to implement an invite system to a webpage I am working on. However when trying to evaluate if there is a row containing the invite code I keep either getting nothing or this warning. The warning in this case but if I change the if state to ==1, it allows everyone regardless of code and ==0 does throws different errors.
if (mysql_query($result)) {
Try mysql_num_rows there.
There are a few things wrong here.
1) SQL Injection vulnerabilities, don't ever pass a superglobal $_POST or $_GET or any other user-supplied variable directly inside your query!
Use at minimum mysql_real_escape_string() to the variable before letting it into the query, or better look into parametrized queries, it's the best way to avoid SQL vulnerabilities
2)
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) ....
This doesn't check if request returns 1 or 0 rows, you should use mysql_num_rows() here instead
if(mysql_num_rows() == 1) //or whatever you need to check
3)
session_start();session_unset();session_destroy();
// start a new session
session_start();
session_start() should be called before anything in your page. Don't know why this redundancy of calling, unsetting, destroying, recalling it here. If you want another id, just use session_regenerate_id();
And as already said by other, use some error reporting in your query, something like
$result = mysql_query($sql) or die(mysql_error())
to actually see what's failed, where and why.
Problem is your query. First of all check your statement and use this :
$result = mysql_query($sql) or die(mysql_error());
instead of this
$result = mysql_query($sql);
So, you can see are there any error at your SQL query .