I have a customer table. Each customer has a specific ID.
In my project(ecommerce website) I want to store the ID of the user in a $_SESSION['user_id'] when he/she successfully login.
How do I do that? What do I need to add?
Here's my code:
<?php
// establishing the MySQLi connection
$con = mysqli_connect("localhost","root","","ecommerce");
// checking the user
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['c_email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "select * from customer where customer_email ='$email' AND customer_pass='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0){
$_SESSION['customer_email']=$email;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Email or password is not correct, try again!')</script>";
}
}
?>
First, as #chris85 mentioned, call session_start() at the top of your script.
Then, you're almost there. First, you need to get the result object from the results.
$rows = array();
while ($row = mysql_fetch_assoc($run_user)) {
$rows[] = $row; // Same as array_push($rows, $row) but has better performance when pushing a single item.
}
Then, assuming we know there is only one row returned:
$customerData = $rows[0];
Cool. Now, set whatever SESSION variables you want:
$_SESSION["user_id"] = $customerData["user_id"];
...
Also, as has been noted in the comments, please please please do not ever store a user's password as plain text. You should hash and salt it. Here is a good starter post to read through: Best way to store password in database
Related
so i'm having trouble and i really have no idea why i'm having this issue because all looks well. But basically i'm trying create multiple user levels for a web page i'm making. For some reason only the regular user role is working at the moment. Basically I want admins to be led to a different user interface. If anyone knows any good content on how to make certain pages only available when a session is started that would be very helpful because that would be my next step after I solve this, also how to create a difference in regular user sessions and admin sessions if that makes sence... But back to my real problem, please tell me why admins arent being led to my admin.php page.. I'm posting the code below.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user = $_POST ['user'];
$pass = $_POST ['pass'];
$reg = '0';
$admin = '1';
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
//this query is for admin users **dont forget to change active to 1 within
db
$qa = "select * from users where username ='$user' and active = '0' and admin = '$admin'";
//this query is for regular users
$q = "select * from users where username ='$user' and active = '0' and admin
= '$reg'";
//these will run the querys above (a = admin)
$resulta = mysqli_query($conn, $qa);
$result = mysqli_query($conn, $q);
//will count rows and verify admin users
$numa = mysqli_num_rows($resulta);
$rowa = mysqli_fetch_array($resulta, MYSQLI_ASSOC);
//will count rows and verify regular users
$num = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($pass,$row['password']))
{
if ($num == 1) {
$_SESSION['username'] = $user;
header('location:index.php');
}
else if (password_verify($pass,$rowa['password']))
{
if ($numa == 1) {
$_SESSION['username'] = $user;
header('location:admin.php');
}
}
}
echo mysqli_error($conn);
?>
your code seems a little confusing to me, so I've sampled it down, instead of running two different queries, why not just one.
Look at this code below, this will help you transfer to admin page when admin logs in, and redirects you to regular page in case of all others.
All I am doing is checking the row value, instead of checking the count again.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user=mysqli_real_escape_string($conn,$_POST['username']);
$pass=mysqli_real_escape_string($conn,$_POST['password']);
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
$sql="select * from users where username ='$user' and active = '0'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($mypassword, $row["pass"])) {
$_SESSION['username']=$user;
if($row["admin"] == "1")
header("location: admin.php");
else if($row["admin"]=="0")
header("location: index.php");
}
else
echo mysqli_error($conn);
?>
I am trying to figure out how to display user information after they've logged in. I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users. I am also having trouble grabbing the header.
here's my code for login.php
<?php
session_start();
require 'dbh.php';
$username = $_POST['uname'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM registeredusers WHERE UserName = '$username'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$hashed_Password = $row['Password'];
$Dehash = password_verify($password,$hashed_Password);
if($Dehash == 0){
echo "username or password is incorrect";
exit();
} else{
$sql = "SELECT * FROM registeredusers WHERE UserName='$username' AND Password='$hashed_Password'";
$result = mysqli_query($connection,$sql);
if (!$row=mysqli_fetch_assoc($result)){
echo "Your User Name or Password is incorrect";
}
else {
$userid = $row['id'];
$_SESSION['UserName'] = $row['UserName'];
header("Location: userhomepage.php?user_id=".$userid);
}
}
?>
The following code redirects to userhomepage.php and the user ID is in the url can someone also tell me how do I grab the user ID from the url? I only started coding in PHP a week ago I am fairly new so if guys have any pointers for me that would be great.
I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users.
You should create a single page that displays user information based on session... you don't want to have to hand-make a new page every time a user signs up!
how do I grab the user ID from the url
echo $_GET["user_id"];
I have a forum page and want a simple login for user with usernames from a predefined mysql user table. I use a login.php form file link from the forum, a get $_POST username, then use a login_handle.php file that calls a function to connect to the DB, query the users array, and try to validate that the $_POST username is in the queried list array.
The function is below, and then the call in login_handle.php I'm getting various errors and don't know if this is at all a good approach. I also want to start a session during the form and verification that can grab the $_POST username as a $_SESSION username and apply to subsequent forum pages.
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users";
$result = mysql_query($query);
$usernames = mysql_fetch_assoc($result);
$isUname = true;
if(!in_array("username", $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
------------------handler call-----------
$username = $_POST["username"];
$password = $_POST["password"];
if(isUsername($username)==true){ // Check if username is valid.
//$Uname = $_SESSION['username'];
//echo "Username = " . $Uname;
echo 'go to forum';
}
First, mysql is deprecated. Please use mysqli.
Second, why don't you use something like...
function isUsername($username){
$query = "SELECT username FROM users WHERE username == '" . $username . "'";
Third: did you search and research?
These kind of question can be easily find everywhere.
As simple as it is , you need to query the specific username from $_POST , not the whole usertable.
I think requesting the number of rows ( number of apparition is a good way to get if user is in database or not , you can make it greater (>=) instead of one user condition (==)).
function isUsername($username){ //Test if proper Username from array.
$query = "SELECT username FROM users where username='$username'";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
$isUname = true;
if($rows==1) {
$isUname = true;
}else{
echo "Please enter valid user name.<br>";
$isUname = false;
}
return $isUname;
}
I used nearly the same function when I manually assigned a txt array to a variable $username to compare. Now that I am using a user table I merely want to assign the an array of the queried users (thought mysql_fetch_assoc($result) creates the same type of assoc. array) to $username instead of the hard copied elements where it worked with before. Is the array produced with the query different than the $usernames=array("jes34","pes22","jis44","jll124"); that prevents me from doing this?
function isUsername($username){ //Test if proper Username from array.
$usernames=array("jes34","pes22","jis44","jll124");
$isUname = true;
if(!in_array($_POST["username"], $usernames)) {
echo "Please enter valid user name.<br>";
$isUname = false;
} //Search for proper username in username array.
return $isUname;
}
-----function call---
if(isUsername($username)==true){ do something }
I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.
So recently I learned how to properly add a username and password to a database.
My database is usersys, and the table storing user information is called userdb. The table has two columns - username (primary), password.
The registration form works great, enters the users input into the database correctly and also checks to see whether the user's username is already in the database or not.
With that said, I am asking if anyone could help me create a login script. So far, this is what I have:
$username = $_POST['username'];
$password = $_POST['password'];
$displayname = $_POST['username'];
$displayname = strtolower($displayname);
$displayname = ucfirst($displayname);
echo "Your username: " . $displayname . "<br />";
mysql_connect("localhost", "root", "******") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("usersys") or die(mysql_error());
echo "Connected to Database <br />";
$lcusername = strtolower($username);
$esclcusername = mysql_real_escape_string($lcusername);
$escpassword = mysql_real_escape_string($password);
$result = mysql_query("SELECT * FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$validateUser = $row['username'];
$validatePass = $row['password'];
The POST data is from the previous log in page. I want this script to check the table (userdb) and find the row for the username that the user entered from the previous form and verify that the password entered matches the username's password set in that row, in userdb table.
I also want some type of way to check whether or not if the username entered exists, to tell the user that the username entered does not exists if it can not be found in the table.
This is not a direct answer to this question but a GOOD value-add.
You should use MYSQL SHA1 function to encrypt the password before storing into the database.
$user = $_POST['userid'];
$pwd = $_POST['password'];
$insert_sql = "INSERT into USER(userid, password) VALUES($user, SHA1($pwd))";
$select_sql = "SELECT * FROM USER WHERE userid=$user AND password=SHA1($pwd))";
You can use sessions. Sessions are global variables that when set, stay with the user while he is browsing through the site.
Since you are learning PHP, try out this tutorial on the official website.
But what you would do in theory is when the username and password match, you set a session variable
$_SESSION["auth"] = true;
$_SESSION["user_id"] = $row["user_id"];
And then do a check to see if the user is authenticated.
One way to do it (DISCLAIMER: not necessarily best-practice):
$result = mysql_query("SELECT id FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$id = (int)$row['id'];
if($id > 0) {
//log in the user
session_start();
$_SESSION['userId'] = $id;
$_SESSION['username'] = $displayname;
}
... and on pages that require authentication:
session_start();
if(!isset($_SESSION['userId'])) {
die('You need to be logged in!!!');
} else {
echo 'Welcome ' . $_SESSION['username'];
}
Read more about PHP sessions.
I like to use both $_SESSION and MYSQL Checks with any login POST. This should help get a few things started.
$username = mysql_real_escape_string($_POST[username]);
$password = strip_tags($_POST[password]);
$password = sha1($password);
if(isset($username) && isset($password) && !empty($username) && !empty($password))
{
$sql = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
//Check the number of users against database
//with the given criteria. We're looking for 1 so
//adding > 0 (greater than zero does the trick).
$num_rows = mysql_num_rows($sql);
if($num_rows > 0){
//Lets grab and create a variable from the DB to register
//the user's session with.
$gid = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
$row = mysql_fetch_assoc($gid);
$uid = $row[userid];
// This is where we register the session.
$_SESSION[valid_user] = $uid;
//Send the user to the member page. The userid is what the
//session include runs against.
header('Location: memberpage.php?userid='.$userid);
}
//If it doesn't check out -- throw an error.
else
{
echo 'Invalid Login Information';
}
}
NOTE: You would need to start the page file with session_start() and create a separate Session Check include stating with session_start() and then your progressions e.g. if($_SESSION[valid_user] != $userid) do something.
You could use a select statement to retreive from MySQL the password for the specified username. If you have an empty result set, then you do not have the username in the table.
If you need the user to be authenticated in more than one php page, then one choice whould be using sessions (http://www.php.net/manual/en/function.session-start.php).
Also, I think you should think about security, i.e. preventing SQL injection:
$variable = mysql_real_escape_string($_POST['variable'])
and avoiding to "die" (treating errors and returning user-friendly messages from the script).
I would also think about not storing passwords in your database. One way hashes with MD5 or SHA1 are a way of adding a layer of security at the db level.
See http://php.net/md5 or http://php.net/sha1 for further information.
I agree with the idea if using SESSION variables while authenticating the user.
The easy way to authenticate the user is as follows
//connect the mysql_db
$mysql_connect()
$mysql_select_db()
//reading from mysql table
$res="SELECT * FROM table WHERE name=$username AND password=$password";
$val=mysql_query($res);
//authentication
$count=mysql_num_rows($val);
if($count==1)
//authenticate the user
else
through an error