Hello I am trying to make multiple users in a CMS I made. I have all their data in a table and was using mysql_num_rows check if the records matched and then use session_register() to set a session. I have changed this to PDO commands.
I want to be able to track the user when they are using the CMS so that every record changed can have their usrID attached to it. So that at a later date I can see who made updates and eventually use this to show information about the author etc.
So for example when they use forms to update or add a new record a hidden input with have their session id echo'd into it which will be taken from their user record as they log in.
Is the best way to do this? Have a written the syntax in this login code correctly?
$con = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql="SELECT * FROM $tbl_name WHERE the_username='$the_username' and the_password='$the_password'";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
if($number_of_rows==1){
$info = $result->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and try again.";
}
Would it perhaps be better to put?
if($number_of_rows==1 && $info = $result->fetch(PDO::FETCH_ASSOC)){MAKE SESSION}
Your usage of PDO functions is quite inconsistent, and it leads to some errors.
First of all, you cannot fetch the same data twice. And, as a matter of fact, you don't need such a double fetch at all.
Also, for some reason you are not using prepared statements which are the only reason for using PDO. So, the proper code would be
$sql="SELECT * FROM $tbl_name WHERE the_username=? and the_password=?";
$result = $con->prepare($sql);
$result->execute(array($the_username,$the_password));
# $number_of_rows = $result->fetchColumn(); <- don't need that
$info = $result->fetch();
if($info){
$_SESSION['username'] = $info['the_username'];
$_SESSION['id'] = $info['id'];
header('Location: admin.php');
}else{
echo "Wrong username or password, please refresh and try again.";
}
Yes the code and logic works fine. But don't use session_register() they are deprecated in new version of PHP.
Related
I am still in the process of learning PHP so forgive me for the poor code.
I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.
<?php
session_start();
$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";
$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
//if there is an issue with connecting to the database, ends code and displays the error
die("failed to connect to server: " .mysqli_connect_error()); //kills program
}
if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
//unable to get data
die("please fill in both email and password"); //kills program
}
$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation
$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match
$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query
$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1
echo "Welcome $dbFirstName <br/> ";
echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page"; //successful login, links to accounts page
$_SESSION['firstName']=$dbFirstName;
}else{ //if matches are 0 or >=2
die ('unsuccessful login'); //kills program
}
?>
Thank you for your time and help
This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.
The mysqli_num_rows() function returns the number of rows in a result set.
$rowsQueryResult = mysqli_num_rows($Queryresult);`
will give number of 'emails' in database where the emails match.
You need to use mysqli_fetch_assoc() as
$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];
I made a signin form that will look through the database and find a match to the user's credentials, but how do I fix this code so it will relocate the page if there is no match.
<?php
session_start();
include_once 'includes/dbh.php';
$username = $_POST['u_name'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM users;";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
if ($username == $row['username'] && $password == $row['password']) {
$_SESSION['username'] = $username;
header("Location: second_index.php?signinSuccessful");
}
if ($username != $row['username'] && $password != $row['password']) {
header("Location: index.php?NotSucessful");
}
}
I tried putting the code inside of the loop, but I know that can't work, and if I put it outside of the loop, It redirects even if the credentials are correct. Please help. Thanks
First of all, this is totally wrong, you're looping trough all the users to see if the user exist, instead of that sql statement try $sql = "SELECT * FROM users where user='$user' and password='$password'";
And to avoid any data breach in that sql statemen you have to serialize the user and pass like that before adding it to the statement
$user = mysql_real_escape_string($conn, $user);
$password =mysql_real_escape_string($conn, $password);
Then you only check if the fields aren't empty (which means the user exist)
You are getting all the users from the users table and checking each record manually in php.
The reason why your code doesn't work is because the while loop doesn't check all the users in user table. If the first record in the retrieved table data doesn't match with entered username and password, it will go to 2nd if block and redirect.
You should change your query to filter by user-entered values.
SELECT * FROM USERS WHERE USERNAME = 'username' AND PASSWORD='password'
And later check in php if any record is returned. If any record is returned, it is a valid user, else redirect the user to failed authentication page.
As a good practice, make sure to use parameterized query.
Update Replace the while loop and block with this.
if(mysqli_num_rows($result) > 0){
// valid user
}else{
// invalid user
}
Why do you need while loop in this case when you fetching data from database? Using sql and make the database fetch the only one correct answer, don't make server site do unnecessary work.
I propose just do simple fetch then if check, no need for while loop at all.
Your logic is always redirect to index.php when username password not correct so of course it will always do so when your while loop on server do not hit the correct user.
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
please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.
I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).