I have made a login system which enables a user to sign in using a previously defined email and password, however in the testing section, I have noticed the passwords say they don't match although I know they are correct as I wrote the test one down as I made it. I cant seem to see why this is happening, I think it may be something to do with my hashing of the passwords but I don't know what.The login page check is from document, login.php:
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$data['email']]);
if(!$row = $stmt->fetch())
{
// email didn't match
$errors['login'] = "Login failed. on email";
}
else
{
// email matched, test password
if(!password_verify($data['password'],$row['password']))
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The insertion to the database with hashing is, from insert.php:
if (isset($_POST['name'])){
$name = $_POST['name'];
}
if (isset($_POST['email'])){
$email = $_POST['email'];
}
if (isset($_POST['password'])){
$pword = $_POST['password'];
}
if (isset($_POST['busName'])){
$busName = $_POST['busName'];
}
if (empty($name)){
echo("Name is a required field");
exit();
}
if (empty($email)){
echo ("email is a required field");
exit();
}
if (empty($pword)){
echo("You must enter a password");
exit();
}
$pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
//insert html form into database
$insertquery= "INSERT INTO `cscw`.`users` (
`accountID` ,
`businessName` ,
`name` ,
`emails` ,
`password`
)
VALUES (
NULL , '$busName', '$name', '$email', '$pword'
);";
and on the web page i am shown from login.php, "Login failed. on password". If you need to see any more code please let me know.
It does not recognize $row['password'].
Be always organized with your query **
1)Prepare
2)Execute
3)Fetch
4)Close
5)THEN YOU EXPLOIT the fetched data.
The fetched data need to be sorted as shown with the returnArray function.
Hoping that there are UNIQUE emails and the $data array exists.Try this.
if(empty($errors))
{
$sql = "SELECT accountID, password FROM users WHERE emails=:emails";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':emails', $data['email']);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->CloseCursor();
$stmt=null;
/* Return the results is a more handy way */
function returnArray( $rows, $string )
{
foreach( $rows as $row )
{
return $row[ $string ];
}
}
if( empty($rows) )
{ // email didn't match
$errors['login'] = "Login failed. on email";
}
else
{ // email matched, test password
if( !password_verify( $data['password'], returnArray($rows,'password') ) )
{
// password didn't match
$errors['login'] = "Login failed. on password";
}
else
{
// password matched
$_SESSION['user_id'] = $row['accountID'];
header('location: welcome.php');
die;
}
}
}
The login Page is not finished the query is not inserting. Be carefull you might be vunerable to SQL injections because your do not escape user manipulated variables.(To strengthen security add a form validation, it will be great).
You have used $pword = password_hash($pword, PASSWORD_DEFAULT)."/n";
I removed ."/n" part. I seems that you are using a concatenation operator '.' to add /n add the end of the password_hash.
Your $insertquery is not finished and not readable. You don't need to insert backticks in your query. And no need to SELECT accountID it will autoincrement (See if A_I for accountID is ticked in your database).
Do something like this in your login page.
/* trim and escape*/
function escapeHtmlTrimed( $data )
{
$trimed = trim( $data );
$htmlentities = htmlentities( $trimed, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' );
return $htmlentities;
}
if ( isset( $_POST['name'] ) ){
$name = escapeHtmlTrimed( $_POST['name'] );
}
if ( isset($_POST['email']) ){
$email = escapeHtmlTrimed( $_POST['email'] );
}
if ( isset($_POST['password']) ){
$pword = escapeHtmlTrimed( $_POST['password'] );
}
if ( isset($_POST['busName']) ){
$busName = escapeHtmlTrimed( $_POST['busName'] );
}
if ( empty($name) ){
echo("Name is a required field");
exit();
}
if ( empty($email) ){
echo ("email is a required field");
exit();
}
if ( empty($pword) ){
echo("You must enter a password");
exit();
}
/*Remove this your adding "./n"*/
$pword = password_hash($pword, PASSWORD_DEFAULT);
//insert html form into database
$insertquery= "INSERT INTO users (businessName ,name ,emails,
password) VALUES (:busName , :name, :email , :pword)";
$stmt = $pdo->prepare($insertquery);
$stmt->bindParam(':busName', $busName);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':pword', $pword);
$stmt->execute();
$stmt->CloseCursor();
$stmt=null;
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 am just learning mysqli prepared statements and now i have run into a problem and could not get a way out of it. It is the registration form and takes in "username" "email" and "password". if username and email already exists in the database then it doesnot allow registeration. i've used post method and the code is as,
//validating email
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL) === true) {
echo "invalid email";
exit();
}
//valid email
else{
//prepared query
$query_name = "SELECT * FROM users WHERE user_name = ?";
$query_email = "SELECT * FROM users WHERE user_email = ?";
//prepared statements
$stmt_name = mysqli_prepare($conn, $query_name);
$stmt_email = mysqli_prepare($conn, $query_email);
//if bind failure
if((!mysqli_stmt_bind_param($stmt_name, "s", $user_name)) && (!mysqli_stmt_bind_param($stmt_email, "s", $user_email))){
echo "bind unsuccessfull";
exit();
}
else{
//if execution fails
if( !mysqli_stmt_execute($stmt_name) && !mysqli_stmt_execute($stmt_email)){
echo "stmt execution failed";
exit();
}
//else if execution success
else{
$result_name = mysqli_stmt_store_result($stmt_name);
$result_email = mysqli_stmt_store_result($stmt_email);
//rows
$row_name = mysqli_stmt_num_rows($stmt_name);
$row_email = mysqli_stmt_num_rows($stmt_email);
echo $row_name;
echo $row_email;
}
}
}
it looks like the first part before && in if condition works and the second doesnot work at all. i have tried registering it with existing "email" in the database but the result is still 0.
the connection is fine and works!
Any help will be appreciated>
Instead of doing so much complex code, use single query to do your job
//validating email
if(!filter_var($user_email, FILTER_VALIDATE_EMAIL) === true) {
echo "invalid email";
exit();
}
else{
$stmt = mysqli_prepare($conn, "SELECT * FROM users WHERE user_name = ? OR user_email = ?");
mysqli_stmt_bind_param($stmt, 'ss', $user_name, $user_email);
if( !mysqli_stmt_execute($stmt)){
echo "stmt execution failed";
exit();
}else{
$result_name = mysqli_stmt_store_result($stmt_name);
$result_email = mysqli_stmt_store_result($stmt_email);
//rows
$row_name = mysqli_stmt_num_rows($stmt_name);
$row_email = mysqli_stmt_num_rows($stmt_email);
echo $row_name;
echo $row_email;
}
}
$query_name = "SELECT * FROM users WHERE user_name = ? OR user_email = ?";
you don't need to check the condition twice at same time.If someone will login through email or username then this query will check for both username and email.
I would be tempted to roll both queries together using an or condition in conjunction with a try/catch block so that you can throw exceptions at certain stages if a condition is not met.
if( !isset( $user_email ) or !filter_var( $user_email, FILTER_VALIDATE_EMAIL ) === true ) {
exit("invalid email");
} else {
try{
if( isset( $user_name, $user_email ) ){
$sql='select `user_name`,`user_email` from `users` where `user_name` = ? or user_email = ?'
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ss', $user_name, $user_email );
$result=$stmt->execute();
if( $result ){
$stmt->store_result();
if( $stmt->num_rows == 1 ){
/* user name &/or email already exists */
$stmt->bind_result( $name, $email );
$stmt->fetch();
printf('whoohoo! - found user "%s" with email "%s"', $name, $email );
} else {
/* no record for username or email*/
/* sql query to insert new user */
}
$stmt->free_result();
$stmt->close();
} else {
throw new Exception('sql query failed to return any results');
}
} else {
throw new Exception('unable to prepare sql');
}
} else {
throw new Exception('username &/or email are missing');
}
}catch( Exception $e ){
echo $e->getMessage();
}
The script doesn't throw any error, but if all the input fields are entered correctly, it just refreshs, and nothing happens.
I have included $salt and $link in header.php.
I might have overdid loops, but I spent couple of hrs trying to figure it out before posting it here.
<?php
if (array_key_exists('username', $_POST)||array_key_exists('pass', $_POST)||array_key_exists('email', $_POST)) {
if ($_POST["username"]!== "" && $_POST["email"]!== "" && $_POST["pass"]!== "" && $_POST['cpass']!== "" ){
if($_POST['pass']==$_POST['cpass']){
if (!mysqli_connect_error()) {
$query = "SELECT `username`, `email` FROM `users` WHERE `username` = '".mysqli_real_escape_string($link, $_POST['username'])."' OR `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($row['username'] == $_POST['username']) {
echo "Username already exists!<br>";
//die("Awe! Someone took this username");
}
if ($row['email'] == $_POST['email']) {
echo "Email has been used once!<br>";
//die(":( Email is in use!");
}else if($row['username'] !== $_POST['username'] && $row['email'] !== $_POST['email']){
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
$query = "INSERT INTO `users`( `username`, `pass`, `email`) VALUES ('$username', '$pass', '$email')";
if(mysqli_query($link, $query)){
echo "You were successfully registered";
} else {
echo "Something went wrong, Couldn't register at the moment!";
}
}
}
}else{
echo "An Error Occured while connecting !";
}
}else {
echo "Password didn't match!";
}
}else{
echo "Field(s) can't be left blank!";
}
}
?>
The problem of your code happens on :
if ($row = mysqli_fetch_array($result)) {
and since you didn't place any else for this "if" you don't see anything happens.
The problem is, this condition becomes true only if email or username is already inside the table.
so if given username and/or email is not already in the table, this condition becomes false and therefore it never reaches to inside block where you want to insert the new data.
There is also a side issue with this and lets say your query fetch 2 rows.. imagine this table.
userid - username - email
1 - user1 - user1#test.com
2 - user2 - user2#test.com
now lets say the given input data are
$_POST['username'] = 'user1';
$_POST['email'] = 'user2#test.com';
this will fetch 2 rows in your users table, but as you didn't make a loop you will only check for first row and it might cause bug or unexpected behavior in your script.
UPDATE : I also made a piece of code based on your code.. hope it helps you...
function validateInputs(){
$keys = array('username','pass','cpass','email');
foreach($keys as $key){
if(!isset($_POST[$key]) || empty($_POST[$key])){
throw new Exception("Field(s) can't be left blank!");
}
}
}
function validatePassword(){
if($_POST['pass'] !== $_POST['cpass']){
throw new Exception("Password didn't match!");
}
}
function checkForUniqueInput($email,$username){
global $link;
$query = "SELECT username, email FROM users WHERE username = '".$username."' OR email = '".$email."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
throw new Exception("Username and/or email already exist");
}
}
function insertNewUser($email,$username,$pass){
global $link;
$query = "INSERT INTO users( username, pass, email) VALUES ('".$username."', '".$pass."', '".$email."')";
if(!mysqli_query($link, $query)){
throw new Exception("Something went wrong, Couldn't register at the moment!");
}
}
if(isset($_POST)){
try{
validateInputs();
validatePassword();
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
checkForUniqueInput($email,$username);
insertNewUser($email,$username,$pass);
echo 'You were successfully registered';
}
catch(Exception $e){
echo 'Error : '.$e->getMessage();
}
}
My question is, when I try to log in with correct password, it still display the error message "You have entered wrong password, try again!".(Register works fine, the part checking if user already exist works fine) Here is the code:
register.php (works):
<?php
include('db_conn.php'); //db connection
session_start();
/* Registration process, inserts user info into the database
and sends account confirmation email message
*/
$_SESSION['email'] = $_POST['email'];
$_SESSION['full_name'] = $_POST['name'];
// Escape all $_POST variables to protect against SQL injections
$full_name = $mysqli->escape_string($_POST['name']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$usertype = $mysqli->escape_string("A");
$hash = $mysqli->escape_string( md5( rand(0,1000) ) );
// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'") or die($mysqli->error());
if (isset($_POST["submit"])){
// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
// header("location: error.php");
}
else { // Email doesn't already exist in a database, proceed...
$sql = "INSERT INTO user (Email, Password, UserType, FullName, Hash) "
. "VALUES ('$email','$password', '$usertype','$full_name', '$hash')";
// Add user to the database
if ( $mysqli->query($sql) ){
$_SESSION['logged_in'] = true; // So we know the user has logged in
$_SESSION['message'] =
"You are registered";
header("location: home.php");
}
else {
$_SESSION['message'] = 'Registration failed!';
// header("location: error.php");
}
}
}
?>
sign_in.php (not working properly):
<?php
include('db_conn.php'); //db connection
session_start();
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM user WHERE Email='$email'");
if (isset($_POST["submit"])){
if ( $result->num_rows == 0 ){ // User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
// header("location: error.php");
}
else { // User exists
$user = $result->fetch_assoc();
echo $_POST['password'].$user['Password'];
if ( password_verify($_POST['password'], $user['Password']) ) {
$_SESSION['email'] = $user['Email'];
$_SESSION['full_name'] = $user['Name'];
$_SESSION['user_type'] = $user['UserType'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: home.php");
}
else {
$_SESSION['message'] = "You have entered wrong password, try again!";
// header("location: error.php");
}
}
}
?>
Don't escape the password hash, it is safe to input directly into the DB:
$mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
to:
password_hash($_POST['password'], PASSWORD_BCRYPT);
I have the following script where the user enters some data from the android phone in order to register.
<?php
include("connect.php");
include("functions.php");
if(logged_in())
{
header("location:profile.php");
exit();
}
$error = "";
$j = new stdClass();
$string = "";
if (isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['email']) && isset($_POST['password'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
//echo $firstName."<br/>".$lastName."<br/>".$email."<br/>".$password."<br/>".$passwordConfirm."<br/>".$image."<br/>".$imageSize."<br/>";
//We need to encrypt our password.
$password = md5($password);
$insertQuery = "INSERT INTO users(firstName,lastName,email,password) VALUES('$firstName','$lastName','$email','$password')";
$result = mysqli_query($con,$insertQuery);
if(!$result){
$j->status = "Fail";
$j->message = "No users in database";
$string = json_encode($j);
echo "No inserted data";
//echo $string;
}else{
$j->status = "success";
$j->message = "Successfully registered";
echo "Data inserted";
$string = json_encode($j);
}
echo $string;
}
?>
Unfortunately nothing happens. I can't even generate JSON from the url itself. For example I enter the url's link
http://localhost/android_reg/
and get nothing back. Shouldn't I get
{
"status":"fail",
"status":"No users in database"
}
when there is not data in the database? Surely there is something wrong with my php code.
No. You shouldn't get anything thing back. The main part of your code checks various $_POST variables to see if they're set. Requesting the page in your web browser is a HTTP GET request, so you'll never see any output because the POST variables will never be set.
Make sure your script generates json-output in any case.
Since the fail-branch is usually shorter I prefer to handle it first. In your case: if there is any POST parameter missing -> bail out.
Your script is also prone to sql injections. Prepared statements can avoid that.
<?php
require 'connect.php';
require 'functions.php';
if(logged_in())
{
header("location:profile.php");
exit();
}
// isset() can take multiple arguments and only returns true if all variables are set
if ( !isset($_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['password']) ) {
$result = array('status'=>'fail', 'message'=>'missing POST parameter(s)');
}
else {
$stmt = $con->prepare('
INSERT INTO
users
(firstName,lastName,email,password)
VALUES
(?,?,?,?)
');
if ( !$stmt ) {
$result = array('status'=>'fail', 'message'=>'prepare failed');
}
else if ( !$stmt->bind_param('ssss', $_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['password']) ) {
$result = array('status'=>'fail', 'message'=>'bind failed');
}
else if ( !$stmt->execute() ) {
$result = array('status'=>'fail', 'message'=>'execute/insert failed');
}
else {
$result = array('status'=>'success', 'message'=>'Successfully registered');
}
}
// single, unconditional exit/output point (ok, except for the if(logged_in())/exit() thing)
echo json_encode($result);