I have two pages of form for the sign up process. Both forms feed into two different tables. users and user_profile. I am looking into using $_SESSIONS to pass a unique attribute from the first page to the second so that that there will be a relationship for each user on both tables. The ID column is incremental so i decided to use the username column because it is unique. Now i am having difficulty passing the username from the first page unto the second page so that i can add it to the insert statement for the sql. My code on the first page is as follows
<?php
session_start();
$_SESSION['message'] = '';
$_SESSION['var_user'] = 'username';
....
username is the name of the field from the formand on the second page, i have
<?php
session_start();
$_SESSION['message'] = '';
$username = $_SESSION['var_user'];
$mysqli = new mysqli("localhost", "root", "", "webdev");
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$houseno = ($_POST['str_number']);
$street =($_POST['str_name']);
$city = ($_POST['city']);
$county = ($_POST['county']);
$postcode = ($_POST['pst_code']);
$skills = ($_POST['skills']);
$_username = ($_POST[$username]);
$sql = ("INSERT INTO users_profile (house_no, street_name, city, county,
postcode, about_me, username) VALUES ('$houseno', '$street', '$city',
'$county', '$postcode', '$skills', '$_username')");
if ($mysqli->query($sql) === true){
$_SESSION['message'] = "Registration succesful! Added $username to the database!";
header("location: index.html");
} else{
$_SESSION['message'] = 'Registration Unsuccessful, Please login and update your information';
}
}
I have tried everything from using hidden input in the form. Doesn't seem to be working. Any help will be appreciated.
You're using $username as an key on the second page:
$username = $_SESSION['var_user'];
...
$_username = ($_POST[$username]);
Instead you should simply define it on the first page:
$_SESSION['var_user'] = $_POST['var_user']
And use it on the second page:
$username = $_SESSION['var_user'];
Related
I am building a website's login page for an assignment. When I hash the password in the file that checks the users details it doesn't match with the stored hashed password in the database. The code always goes to the last else statement and relinks me to the login page with the wrong password sv equal to 1. If I don't hash the password, then copy and paste the hashed password from the database into the login form the login works. If anyone can help this would be greatly appreciated
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"];
$pass1 = $_POST["pass"];
$pass = hash('sha256', $pass1);
if(isset($_SESSION['user_type']))
{
unset($_SESSION['user_type']);
}
include("group_detail.php");
$query = "SELECT * from employee WHERE email = '$email' AND password = '$pass'";
$result_employee = $db->query($query);
$employee_row = mysqli_fetch_assoc($result_employee);
if(!empty($employee_row)){
$_SESSION['id'] = $employee_row['employee_ID'];
$_SESSION['name'] = $employee_row['name'];
$_SESSION['user_type'] = $employee_row['title'];
header('Location: homepage.html');
}else{
$query = "SELECT * from customer WHERE email = '$email' AND password = '$pass'";
$result_customer = $db->query($query);
$customer_row = mysqli_fetch_assoc($result_customer);
if(!empty($customer_row)){
$_SESSION['id'] = $customer_row['customer_ID'];
$_SESSION['name'] = $customer_row['name'];
$_SESSION['user_type'] = 'Customer';
$_SESSION['email'] = $customer_row['email'];
header('Location: homepage.html');
}
else{
$_SESSION['wrong_password'] = 1;
header('Location: login.php');
}
}
The registration code
<<?php
// this code checks all reuired fields are filled in appropriately
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$nameErr = $phoneErr = $emailErr = $passwordErr = "";
$name = $address = $eircode = $email = $password = $phone = "";
$employee_ID = 0;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo $nameErr;
if (empty($_POST["name"])) {
$nameErr = "Your name is required for registration";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and a space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Your phone number is required for registration";
} else {
$phone = test_input($_POST["phone"]);
}
if(empty($_POST['email']))
{
$emailErr = "Your Email is required for registration";
} else {
include ("group_detail.php");
$email_test = test_input($_POST["email"]);
$sql = "SELECT * from customer WHERE email = '$email_test'";
// Checks if another account uses this email
$result = $db->query($sql); // runs the query
$num_rows_3= mysqli_num_rows($result); // counts how many rows the query applies to
if($num_rows_3 == 0){
// Sets email value if no one else has used this email to sign up before
$email = test_input($_POST["email"]);
}
else{
// Lets the customer know this email is already in use
$emailErr = "Another account has previously been registered with this email. If this is you, you can login ";
}
}
if(empty($_POST['pass1']))
{
$passwordErr = "Password required";
} else {
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 == $pass2){
$pass = hash('sha256',$pass1);
// $pass = $pass1;
} else{
$passwordErr = "The passwords you enter must match";
}
}
if(empty($_POST['address']))
{
$address = "";
}else{
$address = test_input($_POST['address']);
}
if(empty($_POST['eircode']))
{
$eircode = "";
}else{
$eircode = test_input($_POST['eircode']);
}
if ($phoneErr == "" && $nameErr == "" && $passwordErr == "" && $emailErr == "")
{
// This code enters the data from the form into the customer table
include ("group_detail.php");
$q = "INSERT INTO customer(";
$q .= "name, phone, password, email, address, eircode";
$q .= ") VALUES (";
$q .= "'$name', '$phone', '$pass', '$email', '$address', '$eircode')";
$result = $db->query($q);
$sql = "SELECT customer_ID FROM customer ORDER BY customer_ID DESC LIMIT 1";
$result1 = $db->query($sql);
$row = mysqli_fetch_assoc($result1);
$_SESSION['customer'] = $row['customer_ID'];
header('Location: homepage.html');
}
}
?>
Solution
Your field is of the incorrect length. When you use the SHA256 hash function you get an output similar to:
ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f // password123
If you're password field is only 15 characters then the saved value will be truncated:
ef92b778bafe771
However, during the comparison the full value from the logon script is used against the truncated version stored in the DB and therefore there is no match. Because, as you can see above, they aren't the same.
To fix you need to ALTER the table so that the field is at least varchar(64). Then new accounts will work as expected (note: old hashes still won't work - they need to be redone!)
Additional information
There are a few other issues with your code...
You shouldn't be putting variables directly into your code. Instead it is preferred to use a Prepared Statement with parametrised queries where you bind the variables later.
Which basically means in the query we use a place holder ? where we want a variable and then bind variables to the place holders later on
This is mainly to prevent SQL injection and protect you from incorrect input
It is best to use the PHP built in functions password_* to hash and verify passwords.
It's more secure than simply using hash
salts are auto-generated which protects you from things like rainbow tables
The default algorithm for password_hash requires a field length of 60+ characters
There's no need to store excess data in SESSION
The data is already stored in the DB so just fetch it as and when needed
It seems that you have one table for customers and another for employees
This isn't a good design there should be one table for users and then you can set flags for employee, customer, supplier etc.
Your test_input function carries out functions that are usually done on display not on save.
Below is a quick re-write that addresses some of the above (note: the below code is not complete it doesn't, for example, carry out all of the same validation - e.g. checking for illegal characters - it's just for illustrative purposes)
Register
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$errors = [];
$name = $_POST["name"] ?? null;
$phone = $_POST["phone"] ?? null;
$email = $_POST['email'] ?? null;
$address = $_POST['address'] ?? null;
$eircode = $_POST['eircode'] ?? null;
$pass1 = $_POST['pass1'] ?? null;
$pass2 = $_POST['pass2'] ?? null;
// Check passwords are the same and assign hash to $pass
$pass = $pass1 === $pass2 ? password_hash($pass1, PASSWORD_DEFAULT) : null;
// Check the required fields are present and not empty
if (!$name || !$phone || !$email || !$pass) {
$errors[] = "Required fields are missing.";
}
// Check if the email address already exists in the DB
$checkEmailExistsSQL = "SELECT COUNT(*) as countEmails FROM user WHERE email = ?";
$checkEmailExistsQuery = $mysqli->prepare($checkEmailExistsSQL);
$checkEmailExistsQuery->bind_param("s", $email);
$checkEmailExistsQuery->execute();
$emailExists = $checkEmailExistsQuery->get_result()->fetch_assoc()["countEmails"];
if ($emailExists !== 0) {
$errors[] = "The email address already exists in the DB";
}
// Check if there were errors and output them; then exit the script
if (count($errors)) {
foreach($errors as $error) {
echo $error, PHP_EOL;
}
exit;
}
include("group_detail.php");
$insertSQL = "
INSERT INTO user
(name, phone, password, email, address, eircode)
VALUES
(?, ?, ?, ?, ?, ?)
";
$insertQuery = $mysqli->prepare($insertSQL);
$insertQuery->bind_param("ssssss", $name, $phone, $pass, $email, $address, $eircode);
$insertQuery->execute();
// Success the user is registered
Logon
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"] ?? null;
$pass = $_POST["pass"] ?? null;
// You can remove the old user id. But you don't need to
//
// There's no need to store excess data on the user in
// the SESSION super global; any data that you need
// access to can be retrieved from the DB at will.
// Copying data into SESSION only eats into memory.
unset($_SESSION["id"]);
// Check that something was submitted for email and password
if (!$email || !$pass) {
echo "Error: all fields need to be completed";
exit;
}
include("group_detail.php");
$sql = "SELECT id, password FROM user WHERE email = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("s", $email);
$query->execute();
// Check to see if the email address is registered.
// Then check to see if the password is a match.
if (
!($user = $query->get_result()->fetch_assoc())
|| !password_verify($pass, $user["password"])
) {
echo "Error: the email address or password isn't correct";
exit;
}
// Success the user is logged on
//
$_SESSION["id"] = $user["id"];
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.
I am coding a "social media site" for a class project, and I am having trouble in one section.
When first registering an account, the user must enter a username and password, and click a submit button. PHP code checks the inputs to make sure they're all valid and that there will not be any duplicates, and if everything passes, it adds in the username and password into a SQL table called "users". Users has 3 columns: username, password, and userID. userID is the primary key.
Once that process is completed, we redirect to a separate page, where the user can enter more personal information, such as first and last name, city, country, etc. This table, called "userInfo" has the columns: firstName, lastName, emailAddress, address, city, country, and userID. userID, once again, is the primary key.
What I'm trying to figure out is how to match the two user ID's in an insert statement. I have a form that gathers all the required information, but I am not sure how to set up the SQL query to make sure that users.userID matches userInfo.userID.
Here's my PHP for users (initial registration)
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
if(isset($_POST['submit'])){
// Get inputs
$username = $_POST['user'];
$password = $_POST['password'];
// Clean inputs and encrypt password
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$password = md5($password);
// Check username not empty
if (empty($username)) {
$error = "true";
$errorMessage = "Please enter a value for your username";
}
// Check username does not already exist
$checkUserQuery = "SELECT username FROM users WHERE username = '$username'";
$checkResult = $conn->query($checkUserQuery);
if($checkResult->num_rows > 0) {
$error = "true";
$errorMessage = "This username already exists";
}
// Username does not exist, add to database
else {
$insertUserQuery = "INSERT INTO users (username, password) VALUES('$username', '$password')";
$insertResult = $conn->query($insertUserQuery);
$_SESSION['username'] = $username;
header("Location: userInfo.php");
}
}
?>
Here's my PHP code so far for userInfo:
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
// Get inputs
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$emailAddress = "fakeEmailAddress#fakeyfakefake.com";
$address = $_POST['address'];
$city = $_POST['city'];
$country = $_POST['country'];
// Clean inputs
$firstName = mysqli_real_escape_string($conn, $firstName);
$lastName = mysqli_real_escape_string($conn, $lastName);
$address = mysqli_real_escape_string($conn, $address);
$city = mysqli_real_escape_string($conn, $city);
$country = mysqli_real_escape_string($conn, $country);
// Validate Inputs (Only validating first and last name, location entries are not required)
if(empty($firstName) || empty($lastName)) {
$error = "true";
$errorMessage = "Please enter your first AND last name";
}
else {
}
}
?>
Apologies if this is super messy. Databases are NOT my strong suit lol.
Many thanks to anyone who can help!
You'll want to get the mysqli_insert_id for your insert into the users table and pass that along (potentially via your $_SESSION) for creation in userInfo.
I am having the problem of displaying the username. My SQL cannot record the username who added the comments....only display the current login username...what should I do? I don't want customers to enter their name again when they insert comments....
<?php
if ($_POST) {
$name = mysqli_escape_string($conn, $_POST['name']);
$supplier = mysqli_escape_string($conn, $_POST['supplier']);
$description = mysqli_escape_string($conn, $_POST['description']);
$remark = mysqli_escape_string($conn, $_POST['remark']);
$price = mysqli_escape_string($conn, $_POST['price']);
$image = mysqli_escape_string($conn, $_POST['image']);
$createdate = mysqli_escape_string($conn, $_POST['createdate']);
$author = ( isset( $_SESSION["username"] ) ? $_SESSION["username"] : "" );
$result = mysqli_query($conn, "INSERT INTO products (name, supplier, description, remark, price, image, createdate,author) VALUES('$name', '$supplier', '$description', '$remark', '$price', '$image', '$createdate','$author')");
if (!$result) {
exit(mysqli_error($conn));
}
redirect('comment.php'); } else { ?>
<?php } ?>
SUBMIT.PHP
<?php
include("common.php");
logincheck();
$action = (isset($_GET["action"]) ? $_GET["action"] : "");
$link = mysql_connect("localhost", "XX", "XX");
mysql_select_db("XX");
$name = $_POST["name"];
$supplier = $_POST["supplier"];
$description = $_POST["description"];
$remark = $_POST["remark"];
$price = $_POST["price"];
$image = '';
if ( isset( $_FILES['image']['name'] ) && trim( $_FILES['image']['name'] ) != "" )
{
$uploaddir = "Products/";
$image = $uploaddir . basename($_FILES['image']['name']);
if ( ! move_uploaded_file( $_FILES['image']['tmp_name'], $image ) ) {
die('Image cannot be uploaded');
}
}
switch($action) {
case "insert":
$sql = "insert into products (name, supplier, description, remark, price, image, createdate) values ('$name', '$supplier', '$description', '$remark', '$price', '$image', NOW())";
mysql_query($sql, $link);
break;
case "save":
$id = $_POST["id"];
$image2 = $_POST["image2"];
if ($image == '')
$image = $image2;
$sql = "update products set name='$name', supplier='$supplier', description='$description', remark='$remark', price='$price', image='$image' where id='$id'";
mysql_query($sql, $link);
break;
case "delete":
$id = $_GET["id"];
$sql = "delete from products where id=$id";
mysql_query($sql, $link);
break;
}
Header( "Location: comment.php" );
?>
This way you can set the session.
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
?>
You can see the session like this echo $_SESSION['favolor']; and it will show green
see http://php.net/manual/en/function.session-start.php
You can use put the username in the $_SESSION object once they're logged in.
Then you can just echo the username; for example:
echo $_SESSION['username'];
In your code the $conn is not initialized anywhere. Initialize it like this before trying the query.
$conn = mysqli_connect("localhost", "my_user", "my_password", "world");
Check the php manual for proper usage.
Hope that helps :)
my suggestion is session , when a user logs in, set a user_login session to 1 ,
and user_name session to the user name.
before every comment,check if user is logged in or not,
if he is not get the name from form,
if he is, hide the name input and save the user_name session in the database.
if you have any problem using session comment on this answer, i will explain , if you want
in the first line of your file(even before any spaces or new lines) you must
add this:
<?php session_start(); ?>
after the user enters his username and password,
you check if they match or not,
you have :
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if username and password matched with username and password stored in database,
do this :
$_SESSION['username']=$username;
$_SESSION['log']=1;
and then , about your comment page :
<?php if(!isset($_SESSION['log']) || $_SESSION['log']!=1) { ?>
Enter your name : <input type='text' name='user_name'>
<?php } ?>
now, if user is logged in, he cant enter his name.
i assume your form posts data to post.php ,
now in post.php you must do this :
<?php
if($_POST['user_name']) $name = $_POST['username']
else $name = $_SESSION['username']
?>
and then, Note: put <?php session_start() ?> in your first line of post.php
after all that, you can insert the comment and name of the user in the database.
good luck with that, if my answer helped you, mark my question as accepted.
I am new to OOP. I want to use the values of class functions in a mySql query. But I am having difficulty retrieving the values. So maybe my method is not correct.
Below is my code and the result. As you can see, the echoed values are empty.
(If the attached code is not sufficient, then please let me know.)
Code:
if(isset($_POST['hidden']))
{
$validator = new FormValidator();
$fname =$validator->addValidation("fname","req","Please fill in First Name");
$email= $validator->addValidation("email","email","The input for Email should be a valid email value");
$lname= $validator->addValidation("lname","req","Please fill in Last Name");
$pass= $validator->addValidation("pass","req","Please fill in Password");
$con_pass= $validator->addValidation("confirmpass","req","Please fill in Confirm Password");
$sname= $validator->addValidation("sname","req","Please fill in Screen Name");
if($validator->ValidateForm())
{
echo $insert_query ="insert into registeration set fname = '".$fname."', lname = '".$lname."', email = '".$email."', pass = '".$pass."', cpass = '".$con_pass."', sname = '".$sname."' ";
mysql_query($insert_query);
Result:
insert into registeration set fname = '', lname = '', email = '', pass = '', cpass = '', sname = ''
Query you are using is more appropriate if you are updating an existing record try this
if($validator->ValidateForm())
{
$fname = $_POST['fname']; // name of your input field
$lname = $_POST['lname'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$con_pass = $_POST['con_pass'];
$sname = $_POST['sname'];
$insert_query = mysql_query("INSERT INTO registeration (fname,lname,email,pass,cpass,sname)
VALUES ('$fname','$lname','$email','$pass','$con_pass','$sname')") or die(mysql_error());
}
( edited ) and reason for not working is because your variables are equal to the instance of methods you are calling you need to make them equal to the input fields.
Hope this can help you