i am using a login script that is suppose to set a session when a user logs in. this session is called '$_SESSION['user']' and is a unique number stored in my table under 'session_number'.
$_SESSION['user'] = 'session_number'
Login Script (login.php):
<?php
include("config.php");
$tbl_name="supplier_pre_sign";
$myusername=$_POST['myusername'];
$myusername = stripslashes($myusername);
$myusername = mysql_real_escape_string($myusername);
$sql="SELECT * FROM $tbl_name WHERE code='$myusername' and status='active'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if($count==1){
session_start();
$_SESSION['user']=$myusername;
$_SESSION['username']=$row['firstname'];
if(isset($_SESSION['val']))
$_SESSION['val']=$_SESSION['val']+1;
else
$_SESSION['val']=1;
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$query = "SELECT * FROM supplier_session WHERE user_IP='$ip'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
}else{
$myusername = filter_input(INPUT_POST, 'myusername');
$ipaddress = $_SERVER["REMOTE_ADDR"];
$sql="INSERT INTO supplier_session (session_number, user_IP, date)
VALUES ('$myusername', '$ipaddress', NOW())";
$result = mysql_query($sql);
}
header("location:supplier_panel.php");
}else {
header('Location: index.php?msg=' . urlencode(base64_encode("Sorry That Code Wasn't Right!")));
}
ob_end_flush();
?>
Once the user logs in the session is suppose to be set. Now i am trying to use $_SESSION['user'] in my MYSQL Update where clause on a different page like so:
(register.php):
$sql="UPDATE supplier_session SET form1_completed = 'Yes' WHERE form1_completed = 'No' AND session_number = ".$_SESSION['user']."";
the problem i am getting is my mysql update script fails, with no error, but i am guessing $_SESSION['user'] is not defined and i somehow need to carry this session over to every page?
Can someone please show me where i am going wrong
One thing you might want to try is putting the session_start() call at the top of the script.
But why re-invent the wheel? This is especially true when it concerns security of your site. You're using database code that leaves you open to SQL injection attacks. I'm gonna guess you're storing user passwords in plain text too. You're just wide open for problems.
You really ought to go with something like http://www.php-login.net.
Related
I'm using this code to login user and I want to update the value in column loggedin to yes in mysql database. I tried to update it before sending header but it doesn't get updated. Where should I put the code to update the column?
if (isset($_POST['login']))
{
$username = trim(mysqli_real_escape_string($con, $_POST['username']));
$password = trim(mysqli_real_escape_string($con, $_POST['password']));
$md5password = md5($password);
// check user and password match to the database
$query = mysqli_query($con, "SELECT * FROM `user` WHERE username='$username' AND password='$md5password'");
// check how much rows return
if (mysqli_num_rows($query) == 1)
{
// login the user
// get the id of the user
$fetch = mysqli_fetch_assoc($query);
// start the session and store user id in the session
session_start();
$_SESSION['id'] = $fetch['id'];
$_SESSION['username'] = $fetch['username'];
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE userid = 1;");
header("Location: message.php");
}
else
{
// show error message
echo "<div class='alert alert-danger'>Invalid username Or password.</div>";
}
}
You're not updating the correct userid. You're updating userid = 1 instead of the ID belonging to the user who logged in. It should be:
$query = mysqli_query($con,"UPDATE user SET loggedin = 'yes' WHERE id = {$_SESSION['id']};");
You need to change this:
UPDATE user SET loggedin = 'yes' WHERE userid = 1;
To this:
mysqli_query($con, 'UPDATE user SET loggedin = 'yes' WHERE userid = 1');
Please don't use the md5() function hashing passwords, it isn't safe, use these functions instead:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php
You also use this:
if (mysqli_num_rows($query) == 1)
To check if the username exists, I suggest changing it to this:
if (mysqli_num_rows($query))
It does the same but you need less code to do it.
Other than that, please also learn how to prepare your queries before inserting them, your current code is vulnerable to SQL injection, more about that can be found here:
How can I prevent SQL injection in PHP?
I am trying to create a login script which checks two tables to see if the username and password exists in the database.
The purpose of having two tables is one is for suppliers/external users and the other is for internal users.
I am having difficulty with my MYSQL query where I am using NOT EXISTS. This causes the query to display the error 'ooops! username or password combination incorrect'.
can someone please show me where I am going wrong here? thanks
session_start();
include("config.php");
$tbl_name="supplier_users";
$tbl_name2="internal_users";
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="select NOT EXISTS (select * from $tbl_name where username = {$myusername} and password = {$mypassword}) AND NOT EXISTS (select * from $tbl_name2 where username = {$myusername} and password = {$mypassword})";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if($count==1) {
session_start();
$_SESSION['user']=$myusername;
$_SESSION['username']=$row['First_Name'];
if(isset($_SESSION['val'])) {
$_SESSION['val']=$_SESSION['val']+1;
} else {
$_SESSION['val']=1;
header("location:../dashboard.php");
}
} else {
echo mysql_error();
$_SESSION['message2'] = '<div id="message_box2"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Oooops!</h23><p>The Username and Password Combination do not match. Please try again.</p> </div>';
header("location:../index.php");
}
ob_end_flush();
Keep it simple
I see no good reason why you don't perform two seperate checks. Make it into a function, with the table name as an argument, and you can reuse the code. Something like this:
function getUserCount($table,$username,$password)
{
$query = "SELECT username
FROM $table
WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query);
return mysql_num_rows($result);
}
(not tested) But please look up more advice about security... if your system is meant to be really secure. Also, the mysql extension of PHP is deprecated.
For some reason my check login script is letting in guests.
I have not made the site live yet so its all good.
I check the database for the username and the password the user puts in the html form but for some reason if it don't even get a result it still sets the username to nil
if it gets the result it sets the username to the username but if it don't get any results it sets the username to nothing.
I have a if statement but still setting it.
$myusername = mysql_real_escape_string($_POST['myusername']);
$mypassword = mysql_real_escape_string($_POST['mypassword']);
$sql = "SELECT * FROM users WHERE username='$myusername'";
$result = mysql_query($sql) or die(mysql_error());
$battle_get = mysql_fetch_array($result);
if ($battle_get['password'] == $mypassword)
{
$_SESSION['username'] = $myusername ; // store session data
header('Location: http://mydomainname.net/new_rpg/dashboard.php');
} else {
echo "wrong password" ;
}
You don't check if the user account actually exists. You just blindly fetch a row from the result set, even if that result set has NO records in it. That means $battle_get will be an empty array (or a boolean false if the query failed). You then do a string comparison against the submitted password. If that password is also empty, you're doing if (empty == empty) and boom... the user's in.
What you SHOULD be doing is:
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = "SELECT ... FROM users WHERE (username = '$username') AND (password = '$password')";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($sql) != 1) {
die("Invalid username and/or password"); // don't tell the user which failed.
}
Checking how many rows were returned is critical - if no rows are returned, then the user doesn't exist or the password is wrong. If 1 row is returned, then it's a valid login. If more than 1 row is returned, you've got duplicate username/password pairs in the database and need to fix that right away.
And, having just seen your "md5 is hard" comment above: You're dead wrong. MD5 is trivially EASY.
When you create the user record, you can hash the password easily:
INSERT INTO users (password) VALUES (MD5('$password'));
and for the login check:
SELECT ... WHERE (password = MD5('$password'));
Nothing to it at all.
Yur mistake:
Say I am not a user.
So $battle_get['password'] = false;
and $mypassword is also false,
so $battle_get['password'] equals $mypassword
Two way you can resolve this.
First, chek the password with sql:
$sql = "SELECT * FROM users WHERE username='$myusername' AND password = '$mypassword'";
or
if(!$battle_get) {
echo "wrong password" ;
}
I am trying to setup a website that will know if a user has logged into the website before. The MYSQL table has a username, password and firstLogin field. The firstLogin field is an integer field containing 1 if the user has not logged and 2 if they have logged in in the past.
The login sysetm logs in and starts a session as it should do therefore i am certain the count is returning the value of 1. The problem that i am having is the website is going straight to homepage.php even if the firstLogin integer is set to 1. The website should be going to welcome.php whilst performing an update operation to change the integer to 2. Ive been staring at this for about a week now. Hope you can help.
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST ['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT username, password,firstLogin FROM $tbl_name WHERE username='".$myusername."' and password= sha1('".$mypassword."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
$row = mysql_fetch_array($result);
print_r($row);
exit;
if ($row ['firstLogin']=="1")
{
$sql2 ="UPDATE $tbl_name SET firstLogin = '2' WHERE username ='".$myusername."'";
session_start();
session_register("myusername");
session_register("mypassword");
header("welcome.php");
}
else
{
session_start();
session_register("myusername");
session_register("mypassword");
header("location:home.php");
}
}else
{
echo "Wrong Username or Password";
}
?>
In addition to Jeff Parker's fixes, I might suggest extracting your session starting code into a function so that you're not repeating your code. I already see your code introducing a copy and paste error.
Also, I think $row['firstLogin'] == 1 would be acceptable, considering that the row will be returning an integer as opposed to a string.
if ($row ['firstLogin']=="1")
{
$sql2 ="UPDATE $tbl_name SET firstLogin = '2' WHERE username ='".$myusername."'";
session_start();
session_register("myusername"); //!! This is possibly an error, you're saving myusername as opposed to $myusername
session_register("mypassword"); // Same as above
header("welcome.php"); // This is possibly an error since the header is missing the "location:" part
}
else
{
session_start();
session_register("myusername");
session_register("mypassword");
header("location:home.php");
}
Can be turned into
if ($row ['firstLogin']=="1")
{
$sql2 ="UPDATE $tbl_name SET firstLogin = '2' WHERE username ='".$myusername."'";
start_session_and_redirect('welcome.php');
}
else
{
start_session_and_redirect('home.php');
}
then place a function ...
function start_session_and_redirect($location){
session_start();
session_register("myusername"); // I'm also wondering if that's supposed to be $myusername instead of "myusername...
session_register("mypassword");
header("location:$location");
}
You have an error in your above code possibly if php doesn't automatically fix it, where welcome.php doesn't have "location:" in front of it, which can be entirely prevented by having a function for the repeat functionality, something you should always be looking to eliminate from your code.
if ($row ['firstLogin']="1") // wrong
You're doing an assignment. It should be a comparison.
if ($row ['firstLogin'] == "1") // right
There's also an error in the query used to retrieve the user data.
// -- This is wrong, missing the ending parenthesis, and will not run.
$sql="SELECT username, password,firstLogin FROM $tbl_name WHERE
username='".$myusername."' and password= sha1('".$mypassword."'";
// -- This includes the ending parenthesis, and should run.
$sql="SELECT username, password,firstLogin FROM $tbl_name WHERE
username='".$myusername."' and password= sha1('".$mypassword."')";
I have gotten a snippet of code to bring back the username and password and see if they match. i now want to set a session varaible to the 'points' value i have in the table which is in the same row as the username and pass.. what could be done?
<?php $username="asdin";
$password="1sdA2";
$database="a75sdting";
$pword = $_REQUEST['pword'];
$uname = $_REQUEST['uname'];
mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
$exsists = 0;
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
break;
}
if ($exsists){
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}
mysql_close();
?>
i want to set $_SESSION['points'] = $row[points] i guess... but i dont think that is correct
<?php
// start session (required on every page that uses sessions
session_start();
// db auth
$username="asdin";
$password="1sdA2";
$database="a75sdting";
// user auth
$pword = $_POST['pword']; // should use either $_POST or $_GET, NOT $_REQUEST
$uname = $_POST['uname']; // should use either $_POST or $_GET, NOT $_REQUEST
// open db connection
$conn = mysql_connect('mysqsdst.com',$username,$password);
#mysql_select_db($database,$conn) or die( "Unable to select database");
// check user
$query = mysql_query("SELECT * FROM `username` WHERE `password` = '$pword' AND `username` = '$uname'");
if(mysql_num_rows($query)){
// user exists
$row = mysql_fetch_assoc($query);
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}else{
header('Location: http://wwsdipts/login.php'); // take them back to login page if incorrect details
}
// close db connection
mysql_close($conn);
?>
I've tidied up your code a bit, please take a look at the notes. It is also worth nothing the following:
You should be using some sort of protection against SQL injections, such as mysql_real_escape_string($_POST['uname']) - the same for password
You need session_start() on all pages that use session variables
You shouldn't use $_REQUEST, use either $_POST or $_GET (read about it)
Do you actually have a table named username? You should read up a bit about DB design, a better name/use for this table would be users as the table will be holding users (a combination of unique ID, username & password.
I don't know what you mean about points, but to access any column name in the "username" table, use $row['column-name'] after it is set ($row = mysql_fetch_assoc($query);)
If you intend on using PHP a lot in the future, you should look up PDO, it's a great class for handling SQL.
you are right, but in this case your array is rows, and it should be in
$_SESSION['points'] = $rows['points']
And it should be in your while loop:
WHILE($rows = mysql_fetch_array($query)){
$exsists = 1;
$_SESSION['points'] = $rows['points']
break;
}
However, it might be better to do something like this:
if(mysql_num_rows($result) == 1) {
//Login Successful
rows = mysql_fetch_assoc($result);
$_SESSION['points'] = $rows['points']
$_SESSION['usern']=$uname;
$_SESSION['logged']=1;
header('Location: http://wwsdipts/logged2.php');
}