I have a connect file which is included in the header of my files. The header contains a session start, and I have checked that the session ID is the same across pages. I am trying to echo the $_SESSION['userFirstName'] within some HTML to display the users name. I cannot figure out why it it is blank. There are no error messages from Chrome other than the "Notice: Undefined index: userFirstName
Here is my connect.php
<?php
/*Login handled here*/
$servername = "localhost";
$usernameDB = "root";
$passwordDB = "";
$nameDB = "teacheasy";
//set user and password to values from form
if ( isset($_POST['username']) && isset($_POST['password']) ) {
$user = $_POST['username'];
$pass = $_POST['password'];
} else {
echo "The values weren't sent";
}
//connect to the database
$_SESSION['connection'] = new mysqli($servername, $usernameDB, $passwordDB,$nameDB);
//Check if the connection was successful
if($_SESSION['connection']->connect_error){
die("Connection to the database failed: " . $_SESSION['connection']->connect_error);
} else{
//once the DB is connected, get information from the DB to check the records against the data entered
$sqlUser = "SELECT `teacher_username` FROM `teacher` WHERE `teacher_username`='$user'";
$sqlPass = "SELECT `password` FROM `teacher` WHERE `password`='$pass'";
$resultUser = mysqli_query($_SESSION['connection'], $sqlUser);
$resultPass = mysqli_query($_SESSION['connection'], $sqlPass);
$textUser = $resultUser->fetch_assoc();
$textPass = $resultPass->fetch_assoc();
//get first name and last name to populate the user
$sqlUserFirstName = "SELECT `first_name` FROM `teacher` WHERE `teacher_username`='$user'";
$sqlUserLastName = "SELECT `last_name` FROM `teacher` WHERE `teacher_username`='$user'";
$resultUserFirstName = mysqli_query($_SESSION['connection'], $sqlUserFirstName);
$resultUserLastName = mysqli_query($_SESSION['connection'], $sqlUserLastName);
$_SESSION['userFirstName'] = $_POST[$resultUserFirstName->fetch_assoc()];
$_SESSION['userLastName'] = $_POST[$resultUserLastName->fetch_assoc()];
//check if the user and password match records in the database
if($user == $textUser['teacher_username'] && $pass == $textPass['password']){
//open the calendar if they match
echo "<script> window.location.assign('../calendar.php'); </script>";
} else{
//set this up to load a log in failed page rather than a blank page with error message
echo "The data entered has no match.";
}
}
This is what you done
$user = $_POST['username']
// "SELECT `first_name` FROM `teacher` WHERE `teacher_username`='$user'" // SQL injection here
$_SESSION['userFirstName'] = $_POST[$resultUserFirstName->fetch_assoc()];
As #jeroen said in comments $_SESSION['userFirstName'] must be empty because there is no key in the $_POST that is equals $resultUserFirstName->fetch_assoc() which returns an array! . You should be getting an undefined index error.
$_POST is an array that holds the variables that have been posted with the http request to your server. It has nothing to do with the data returned from your database query unless $_POST['username'] === teacher.first_name and teacher.first_name === teacher.teacher_username
try
$_SESSION['userFirstName'] = $resultUserFirstName->fetch_assoc()['first_name'];
instead of
$_SESSION['userFirstName'] = $_POST[$resultUserFirstName->fetch_assoc()];
Also you are vulnerable to SQL injection attacks, and you should make it a happit to always use prepared statements. Check this answer on how to switch to prepared statements if you are used to concatenating.
Related
I was here yesterday with the same issue, but I have changed the code slightly. I am trying to fetch the user id of a user as they log in and store it as a session variable. I don't know what I'm doing wrong though, as when I try pass this session variable into another SQL INSERT statement in a different php file, it does not work. If I pass a local variable to the INSERT statement it works and inserts all values into my database. When I try pass the session variable, it does not work.
This is my login file where I declare the session variable:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['Login_Btn'])) {
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$id_retrieve = mysqli_query("SELECT user_id FROM userdetails WHERE email='$email'");
$retrieved_id = mysqli_fetch_row($id_retrieve);
$password = md5($password);// Decrypt hash of password stored in database
$mySQLQuery = "SELECT * FROM userdetails WHERE email='$email' AND password='$password'";
$resultOfQuery = mysqli_query($db, $mySQLQuery);
if (mysqli_num_rows($resultOfQuery) == 1) {
$_SESSION['user_id'] = $retrieved_id[0];
header("location: User_Home_Page.html");
}else{
$_SESSION['message'] = "Login Fail";
header("location: User_Login.html");
}
}
?>
This is the file where I then try insert this session variable:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['upload_btn'])){
$user_id = $_SESSION[ 'user_id' ];
$taskTitle = mysql_real_escape_string($_POST['tasktitle']);
$taskDescription = mysql_real_escape_string($_POST['TaskDescription']);
$file = rand(1000,100000)."-".$_FILES['file_document']['name'];
$file_loc = $_FILES['file_document']['tmp_name'];
$file_size = $_FILES['file_document']['size'];
$file_type = $_FILES['file_document']['type'];
$folder="uploads/";
move_uploaded_file($file_loc,$folder.$file);
$numPages = mysql_real_escape_string($_POST['number_of_pages']);
$numWords = mysql_real_escape_string($_POST['number_of_words']);
$deadlineClaim = mysql_real_escape_string($_POST['deadline_claim']);
$deadlineComplete = mysql_real_escape_string($_POST['deadline_complete']);
$sql = "INSERT INTO task(user_id, title, description, file, file_type, file_size, pg_num, num_words, deadline_claim, deadline_completion) VALUES( '$user_id', '$taskTitle', '$taskDescription', '$file', '$file_type', '$file_size', '$numPages', '$numWords', '$deadlineClaim', '$deadlineComplete')";
mysqli_query($db, $sql);
header("location: User_Home_Page.html");
}
?>
If someone could provide a solution I would really appreciate it.
First you don't need 2 query because you need a query where you get user_id based on data where user must login.
So in this query first u check for email and password to match that user and if this match u will get more that 0 based on mysqli_num_rows.
When u check this and this works you use mysqli_fetch_array so you can use a data from it however you want.
You can remove error_reporting, ini_set, var_dump if its all ok, this is just for testing and to give you error if exists
Here is your code:
<?php
// turn on error reporting
error_reporting(1);
ini_set('error_reporting', E_ALL);
// start session
session_start();
// debug session
var_dump($_SESSION);
// database connection
$db = mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['Login_Btn']))
{
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
// Decrypt hash of password stored in database
$password = md5($password);
// get all data from userdetails table
$mySQLQuery = "SELECT * FROM userdetails WHERE email='$email' AND password='$password'";
$resultOfQuery = mysqli_query($db, $mySQLQuery);
// if query return more that 0 rows
if (mysqli_num_rows($resultOfQuery) > 0)
{
// fetch data
$uid = mysqli_fetch_array($resultOfQuery);
$_SESSION['user_id'] = $uid['user_id'];
header("location: User_Home_Page.html");
exit();
}
else
{
$_SESSION['message'] = "Login Fail";
header("location: User_Login.html");
exit();
}
}
?>
EDIT :
Don't use md5 its not secure use password_hash() and password_verify() to make yours password safe.
im new at programing and php, and i want to create an error on my registration system that when the user creates an account with the same username already existing in the database it says something like this: "Username already in use" and then if it isnt an existing username it says "Registation Complete"
I tried this code:
<?
require ("conect.php");
$user = $_POST['user'];
$pass = $_POST['password'];
$email = $_POST['email'];
$email_check = $_POST['email_check'];
$register = mysql_fetch_array;
if($user = $register[user]) {
echo"Username already in use";
}
else
{
$insert = mysql_query("INSERT INTO registration (user, password, email)
VALUES('$_POST[user]','$_POST[password]','$_POST[email]')");
echo "The account $user was successfully created.";
}
?>
But it didnt work, can someone help please
As pointed out by the other users, you should be using prepared statements through PDO (or mysqli, but I definitely prefer PDO)
You're storing the POSTS in variables, but then in the database query you are just using the $_POST variable again?
I'm not sure what your doing with the $register = mysql_fetch_array part, but to get the desired functionality you should use a select query to count the number of users using the username.
You're not using any secure hash format to store the password. I switched it to use password_hash().
Try something like this (I haven't tested the code yet though, so there might be errors):
<?php
//Put all POSTS in variables
$user = $_POST['user'];
$pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
$email_check = $_POST['email_check'];
//Database config- probably should store in a separate file
$database_host = "";
$database_name = "";
$database_user = "";
$database_password = "";
$conn = new PDO("mysql:host=$database_host;dbname=$database_name",$database_user,$database_password);
//Find out if the username is taken.
$sql = "SELECT count(*) FROM `registration` WHERE user = :user";
$q = $conn->prepare($sql);
$q->execute(array(':user' => $user));
$number_of_rows = $q->fetchColumn();
//Clear $sql and $q so you can use them again
$sql = NULL;
$q = NULL;
if ($number_of_rows > 1) {
//Username already taken
echo "Username already taken";
}
else {
$sql = "INSERT INTO registration (user,password,email) VALUES (:user,:password,:email)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$user, ':password'=>$password, ':email'=>$email));
echo "The account " . $user . " was successfully created";
}
?>
You really, really need to read about prepared statements. The method you are using is very old, incredibly insecure, and generally a bad-practice by today's standards.
Your code isn't even worth fixing for these reasons, it should be re-written using prepared statements.
I have this problem with my web system. As administrator, my purpose is to register some users giving them username,password,firstname and lastname. I do that properly since all the records are inserted correctly. But when I'm trying to have access as one of those users, I cannot enter, geting the message "Username and password do not match". This is my login check code:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $_POST['username'];
if ((!$username) || (!$password)) {
do_html_header('');
echo '<h3 style="color:#800000;">Please fill in both fields</h3><br><br></br></br>';
display_login_form();
}
else {
$sql = mysql_query('SELECT * FROM members WHERE username="'.$_POST['username'].'" AND password=sha1("'.$_POST['password'].'")') or die(mysql_error());
$login_check_member = mysql_num_rows($sql);
if($login_check_member > 0) {
while($row = mysql_fetch_array($sql)) {
$role = $row["role"];
$_SESSION['role'] = $role;
}
}
else { // Run this code if login_check is equal to 0 meaning they do not exist
do_html_header('');
echo '<h3 style="color:#800000;">The Username And Password do not match.</h3><br><br></br></br>';
display_login_form();
}
Apparently, there is a problem with my while loop. But it does work properly for those users inserted in my database via MySql console of wampserver. The problem exists only for the users inserted via the web site.
The part of code that I use to insert new users (servers) is :
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$role = $_POST['role'];
$conn = mysql_connect("localhost", "root", "");
$db=mysql_select_db("buzzcafe" ,$conn);
//$username= $_SESSION['username'];
if (isset($_POST['username'])) {
if (isset($_POST['password'])) {
if (isset($_POST['firstname'])) {
if (isset($_POST['lastname'])) {
if(isset($_POST['role'])) {
$insertServer = mysql_query("INSERT INTO servers (username,password,firstname,lastname,role) VALUES('".$username."',sha1('".$password."'),'".$firstname."','".$lastname."','".$role."')")or die(mysql_error());
echo "<h5 style=color:#800000><i>The server ".$username." is now registered </i></h5>";
display_manager_menu();
}
}
}
}
}
Any ideas please?
Look at the table you INSERT the data ('servers'). It's different from the table you SELECT the data from ('members').
Don't use the mysql_query function, as it deprecated. Try using PDO or mysqli_query instead.
Don't ever use unfiltered input in your query.
Try using more secure functions for your login/registration form (like bcrypt, or password_hash). Look here.
I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
This is my code
$username = $_POST['user'];
$password = $_POST['pass'];
if (isset($_POST['user'])); {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")){
while($row = mysqli_fetch_assoc($query)){
$row['pass'] = $setpassword;
}
mysqli_free_result($query);
}
}
What it currently does is from a form, retrive a username and password that the user has entered, take that username and find the row with that username and get the password from that row and set it as the variable $setpassword. Below is the code to check if the password matches the given username on the database.
if ($password=='') {
$verify = 0;
}
if ($password!='') {
if ($password!=$setpassword) {
$verify = 1;
}
if ($password==$setpassword) {
$verify = 2;
}
}
If verify is...
0 - The Login Form Will appear as nothing has been entered.
1 - Incorrect Password will be displayed along with the login form.
2 - Correct Password will be displayed and the username will be assigned to a session variable.
I'm having a problem where a user can enter a username that doesnt exist and any password wether its in the database or not and it will be verified.
What can I do to check if the username doesn't exist on the database?
When you are accepting the user's registration query the database to see if it already exists.
$result = mysqli_query("SELECT * FROM accounts where `user` = $username");
if(mysql_num_rows($result) >0) // if there are any rows returned then the username exists
{
//User Name already exists
}
else
{
//User name doesn't exist, add user
}
I'm not sure this is where you are doing that. But to eliminate duplicates you can do it that way. Also, you can define the column user as unique. That way the SQL will not allow duplicate values.
Also this line:
$row['pass'] = $setpassword; //setting $row['pass'] to $setpasswords value.
This is reversed. You should be doing it the other way around.
$setpassword = $row['pass']; //setting setpassword to $row['pass'] value.
Let me know if I need to clarify anything.
Try this:
$username = isset($_POST['user'])?$_POST['user']:''; // check if isset to avoid notice
$password = isset($_POST['pass'])?$_POST['pass']:'';
$verify = 0;
if (!empty($username)) {
$db = mysqli_connect('localhost', 'root', '', 'db');
if($query = mysqli_query($db, "SELECT `pass` FROM `accounts` WHERE `user` = '$username'")) {
while($row = mysqli_fetch_assoc($query)){
$setpassword = $row['pass'];
break; // exit the loop once you found the password
}
mysqli_free_result($query);
}
if (isset($setpassword)) {
$verify = 1;
if ($password == $setpassword) {
$verify = 2;
}
}
if (isset($_POST['user'])); {
there is an extra semicolon in this line, making whole code not working
to do your verification, all you need is to retrieve the password and compare it with entred one:
$row = mysqli_fetch_assoc($query));
if ($row AND $row['pass'] == $password)
$verify = 1;
}
note that $row could be ampty, so, you have to check it first
however, you can do both comparisons in the query, like this
"SELECT * FROM accounts where `user` = $username" AND `pass` = '$password';
However, your code suffers from 2 common problems.
It is better to save a hash instead of the plain password.
You should sanitize your data before adding it in the query
at least this way:
$username = mysqli_real_escape_string($db,$_POST['user']);