I am trying to build a social app using Lua(Corona SDK). What I want to do is save the user in a session when they login/register so they won't have to login whenever they close the app and open it again.
I am sort of confused because I don't really know much Lua but my code doesn't work. I am using PHP and MySQL as the backend and DB. I already save the user in a session in PHP but how do I show the session id to the front end and verify it so that I can automatically login in ?
local function networkListener( event )
if ( event.isError ) then
local alert = native.showAlert("Error Logging In", "Check your internet connection .", {"Try again" })
else if event.response == "success" then
-- put the code here to go to where the user needs to be -- after a successful registration
--username = userID
composer.setVariable( "username", username.text )
composer.gotoScene( "feed", { params = parametersToSend } )
composer.removeScene( "login" )
else -- put code here to notify the user of the problem, perhaps -- a native.alert() dialog that shows
--them the value of event.response -- and take them back to the registration screen to let them try
--again
local json = require("json") print( json.prettify( event ) )
local alert = native.showAlert( "Error Logging In", event.response , { "Try again" } )
end
end
end
local function userLogin(event)
if ( "ended" == event.phase ) then
if emptyFields() == true then
else
local parameters = {}
parameters.body = "Login=1&username=" .. username.text .. "&pw=" .. pw.text
local URL = "http://192.168.1.37/hashmobile/process2.php"
network.request(URL, "POST", networkListener, parameters)
local headers = {}
headers["Content-Type"] = "application/x-www-form-urlencoded"
headers["Accept-Language"] = "en-US"
parameters.headers = headers
end
end
end
process2.php:
$sql = "SELECT pw FROM users WHERE username = ?";
$stmt = mysqli_prepare($con, $sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($hashed_pwd); // Binds variables to a prepared statement for result storage
$stmt->fetch(); // Fetch results from a prepared statement into the bound variables
if (password_verify($pw, $hashed_pwd)) {
//session_id($_POST['user_session_id']); //starts session with given session id
// password verified
$_SESSION["user_session_id"] = $username;
echo "success";
//echo $_SESSION["user_session_id"];
//header('Location: profile.php');
//die();
} else {
//echo 'Incorrect username or Password.';
die('Incorrect username or Password.');
}
That is how I login to my app. Any help ?
Related
The goal is to create profile settings page, where users can change their email address, but before updating ask them to enter their password.
So, I need to fetch password from database and compare it to password entered by user, and if they match update email address.
But, when I try to implement logic, I get a blank page. Code work till query. It stop working when $passwordCheck = true and $resultCheck = 0 (see edited below).
Edited (2019.01.09): redirects work till header('Location: ../edituser.php?success=emailupdate'). When enter new email, correct password and click submit button, it shows changeemail.php (my action script) page instead of redirect to edituser.php with success messsage. I assume that something get broken and script stuck. Also, added complete script.
Edited (2019.01.10): my question is: how to implement password confirmation before updating data using PHP. Above description shows how I tried to implement it. I'm looking for information about solution, different approaches to this problem or some help with my code. Sorry if I not clarify my question detailed enough. I also add profile settings picture below.
Picture 1. Profile settings page
changeemail.php script:
// Check for submit
if (isset($_POST['submit'])) {
// Get form data
$update_id = $_POST['update_id'];
$email = test_input($_POST['email']);
$confirm_password = test_input($_POST['confirm_password']);
// Store post id in session
session_start();
$_SESSION['update_id'] = $update_id;
// Check for empty field
if (empty($email)) {
header('Location: ../edituser.php?error=emptyemail');
exit();
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Check email
header('Location: ../edituser.php?error=invalidemail');
exit();
} else if (empty($confirm_password)) {
header('Location: ../edituser.php?error=emptyconfirmpassword');
exit();
} else {
// Check if email already exist
$query = "SELECT email, password FROM users WHERE email = ?";
// Create prepared statement
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
header('Location: ../edituser.php?error=sqlerror');
exit();
} else {
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $email, $password);
$resultCheck = mysqli_stmt_num_rows($stmt);
while (mysqli_stmt_fetch($stmt)) {
// Check if passwords match
$passwordCheck = password_verify($confirm_password, $password);
if ($passwordCheck == false) {
header('Location: ../edituser.php?error=wrongconfirmpassword');
exit();
} else if ($passwordCheck == true && $resultCheck > 0) {
header('Location: ../edituser.php?error=emailtaken');
exit();
}
// Update email
$query = "UPDATE users SET email = ? WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
header('Location: ../edituser.php?error=sqlerror');
exit();
} else {
mysqli_stmt_bind_param($stmt, 'si', $email, $update_id);
mysqli_stmt_execute($stmt);
header('Location: ../edituser.php?success=emailupdate');
exit();
}
}
}
}
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($conn);
} else {
header('Location: ../edituser.php');
exit();
}
As I said before - check your logic......
Sometimes that is best done in a 'reverse' manner - - - for instance, in this case, you say
When enter new email, correct password and click submit button, it shows changeemail.php (my action script) page instead of redirect to edituser.php with success messsage. I assume that something get broken and script stuck.
So, in other words....
EXPECTED RESULT: redirect to edituser.php
CURRENT RESULT: shows emailupdate (this is not clear in the question, though I believe that this is the case - you are redirecting to edituser.php?success=emailupdate. If this is not the case, clarify! My example below will presume this....)
So, let's follow the logic...... (remove all non-logic and/or redirection code to find why it is hitting where it is....)
First, let's look at why it isn't going where you want......
(EXPECTED RESULT: redirect to edituser.php)
Removing all code except what you expect, we get
// Check for submit
if (isset($_POST['submit'])) {
// DO ALL SORTS OF STUFF
} else {
// NEVER SELECT THIS IF THERE IS A 'SUBMIT' POSTED
header('Location: ../edituser.php');
exit();
}
However, to get to this page, you HAVE a 'submit', so the 'expected' line will NEVER be selected!
Now, let's look at what IS happening - and why......
// Check for submit
if (isset($_POST['submit'])) {
// Get form data
$update_id = $_POST['update_id'];
$email = test_input($_POST['email']);
$confirm_password = test_input($_POST['confirm_password']);
// Check for empty field
if (empty($email)) {
// WE HAVE EMAIL, SO THIS IS NOT HIT
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Check email
// EMAIL IS OK, SO NOT HIT
} else if (empty($confirm_password)) {
// PASSWORD IS OK, SO NOT HIT
} else {
// EMAIL FOUND SO WE ARE HERE
while (mysqli_stmt_fetch($stmt)) {
// Check if passwords match
$passwordCheck = password_verify($confirm_password, $password);
if ($passwordCheck == false) {
// PASSWORD IS OK, SO NO HIT
} else if ($passwordCheck == true && $resultCheck > 0) {
// OK, SO NO HIT
}
// Update email
$query = "UPDATE users SET email = ? WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
// NO FAILED SQL, SO NO HIT
} else {
// NO OTHER LOGIC, SO THIS _WILL_ BE A HIT........
// *****************************************
header('Location: ../edituser.php?success=emailupdate');
exit();
// *****************************************
}
}
}
}
}
Again, it is clear from your code that you will get the results you describe.
What I'm not sure of is really what you are expecting to do (so I can't really recommend code for you), though certainly the logic you are using is taking you where you are telling it to go - even though it is not what you would like to happen.....
You may need an additional check somewhere (to determine if you really need to update the email or just send them to the edituser page, etc.) - though you have to get the logic straight!
Hopefully this will show you a couple ways you can break down the code to get where you are wanting to go. I often START writing code with comments - then go back and fill in the logic with code. This both gives a simple way to follow along with the steps and gives well commented code for later debugging. I highly suggest you use such a system for your coding - certainly when starting out it is useful, but having well commented code will serve you well throughout your life.
To fix my issue I add another query:
$query = "SELECT password FROM users WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $query)) {
header('Location: ../index.php?error=sqlerror');
exit();
} else {
mysqli_stmt_bind_param($stmt, "i", $update_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
Old query won't find password for updated email, because it's not exist yet, and will close connection.
I want to add a condition where if the email is admin#example.com and password is admin, then the admin will be redirected to admin.html, which is different to what a normal user will be redirected to (user.html). P.S. the admin and users are in the same table. Thanks in advance.
<?php
require_once ('../../connect.php');
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
if ($user_email != NULL AND $user_password != NULL)
{
$login = "SELECT * FROM tblusers where user_email = '$user_email' AND user_password = '$user_password' AND user_type=0";
$result = mysqli_query($dbc, $login);
if (mysqli_num_rows($result) >0 )
{
setcookie('user_email', $user_email);
setcookie('user_password', $user_password);
echo '<script type="text/javascript"> window.location ="register.php"; </script>';
}
else
{
echo '<script type="text/javascript"> alert("The email or password you have entered may be incorrect"); window.location ="login.html"; </script>';
}
}
else ($user_email != NULL AND $user_password != NULL)
{
$login = "SELECT * FROM tblusers where user_email = '$user_email' AND user_password = '$user_password' AND user_type=1";
$result = mysqli_query($dbc, $login);
if (mysqli_num_rows($result) >0 )
{
setcookie('user_email', $user_email);
setcookie('user_password', $user_password);
echo '<script type="text/javascript"> window.location ="members.php"; </script>';
}
else
{
echo '<script type="text/javascript"> alert("The email or password you have entered may be incorrect"); window.location ="login.html"; </script>';
}
}
else
{
echo '<script type="text/javascript"> alert("Please enter your email and password in the relative fields"); window.location ="login.html"; </script>';
}
mysqli_close($dbc);
?>
Hmm, your post makes it really difficult to properly provide an answer, but I will try. Before that, know that #RiggsFolly really has made the most important point - get a better tutorial. I would use comments because there are some things that could be clarified but my reputation does not allow me to do that yet. So here goes an attempt at an answer.
What exactly is the logic you are trying to implement? It seems to roughly be:
if (user provides credentials AND credentials exist in database AND credentials are for user_type == 0) {
save credentials;
send user to registration page;
} else if (user provides credentials AND credentials exist in database AND credentials are for user_type == 1) {
save credentials;
send user to members page;
} else {
send user to login page;
}
We can streamline this logic a bit:
if (user has provided credentials) { // if this fails, user is sent to login page
// Now check if credentials exist in database
// Notice I am using comments? Use them to make your code more readable and to better explain what you're doing/what you did!!!
// Query the database only for matching username and password first.
$login = "SELECT * FROM tblusers where user_email = '$user_email' AND user_password = '$user_password'";
$result = mysqli_query($dbc, $login);
// If this returns a match, then check for user_type. Otherwise, prompt user to provide correct credentials.
if (mysqli_num_rows($result) > 0 ) {
// Obtain the results of the query in an associative array so that you can easily access the value of 'user_type'
$row = mysqli_fetch_assoc($result);
// We have confirmed that the credentials exist. So we can save them
// But as RiggsFolly correctly points out, PLEASE look for alternatives more secure than cookies
save credentials;
// Now check the value of user_type and respond accordingly
if ($row["user_type"] == 1) { // admin
send user to admin page; // which seems to be members.php;
} else { // user
// I assume there is no other user_type.
// If there is, make this an elseif statement that checks if user_type == 0
send user to user page; //which seems to be register.php
}
} else {
display message that credentials are incorrect;
send user to login page;
}
} else {
send user to login page;
}
Again, read ALL the links provided by #RiggsFolly and implement them. As he pointed out, we try to improve your code not to write it for you, which is why I tried to stick to the code you provided.
I do hope this helps you. Wish you the best as you learn.
Developing Hybrid App I know it is possible to use php session. Anyone know how it works? I would like to display all the info of the user logged-in on their home page like, fullname, contact no., address, etc.
The login: (login.html) This is the code with ajax:
function handleData(responseData) {
var response = JSON.parse(responseData);
var access = response.user_access;
if (access == "real") {
alert("Welcome");
location.href = "home.html"; //should redirect and auto display all the info.
} else {
alert("Your username and password didn\'t match.");
}
}
So the login page send request to the server to log-in.
Now the server side(PHP) code.
if(isset($_POST['input_email']) && isset($_POST['input_password'])){
$post = $_POST;
array_walk_recursive($post, 'clean');
//SQL query here- check if email/password match
$using = 'real';
}
if($user['user_status'] == 'active'){
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['user_email'] = $user['user_email'];
$_SESSION['user_fullname'] = $user['user_fullname'];
}else{
$using = 'notmatch';
}
Declare variable for session:
$user_fullname = $_SESSION['user_fullname'];
$user_id = $_SESSION['user_id'];
$user_email = $_SESSION['user_email'];
$result_array = array( user_id => $user_id, user_fullname => $user_fullname, user_email => $user_email, user_access => $loggedinusing);
echo json_encode($result_array);
}
Login was working well and redirected to the home page when login credentials are right. My home.html for now don't have any code. I need for now is to display the user info in home page with PHP session. I don't know where to start.
I am trying to display the error at the end if the use doesn't enter the correct combination of their log in. However, the error message is not showing when I enter the wrong password or email. Any suggestions
<?php
include ("connect.php");
if (isset($_POST["user_login"]) && (isset($_POST["user_pass"]))){
// formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','',
$login_user = $_POST["user_login"];
$login_password = $_POST["user_pass"];
// password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
$decrypted_password = md5($login_password);
// Query which finds user (if valid) from DB - Achieving authentication via username and password
$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1");
$check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_user==1){
while ($row = mysqli_fetch_array($user_query)){
$id = $row['user_id'];
$user_type = $row['account'];
}
$_SESSION["user_login"] = $login_user;
// check the user type and redirect according to it
if($user_type == "Student"){
$student_page = "profile_student.php";
header( "Location:{$student_page}" );
} elseif ($user_type == "Landlord"){
$landlord_page = "landlord_profile.php";
header( "Location:{$landlord_page}" );
} elseif ($user_type == "Administrator"){
$admin_page = "admin_profile.php";
header( "Location:{$admin_page}" );
}else {
$refresh_page = "sign_up.php";
header( "Location:{$refresh_page}" ); // refresh page
echo "You have entered an incorrect email or password. Please try again.";
}
}
}
?>
you redirect user if input data is wrong and only after that you try to echo message, thats not how that works. read about headers in php_manual. probably the best way here, is to store error message in session and after redirect check if session error message exists
else {
$refresh_page = "sign_up.php";
$_SESSION['error'] = "your error message"
header( "Location:{$refresh_page}" ); // refresh page
}
in sign_up.php file check if error message exists in session
if(isset($_SESSION["error"])){
echo $_SESSION["error"];
unset($_SESSION["error"]);
}
maybe you should correct this code a little bit))
use unset cause' after you show the message it should be removed from session, in other case if you fail for example 5 times, it will show 5 messages)) also make sure that session is started session_start() hope it helps:)
You only display the error when $user_type doesn't match any of your expected types.
You need a second else after your if ($check_user==1){ block to handle the case where a user with that email or password doesn't exist.
Okay.. I am completely new to this PDO stuff.. I have tried to recreate my mysql script (working) to a PDO script (not working).. I have tested that my DB login informations is correctly programmed for PDO..
This is my PDO script...
<?
session_start();
//connect to DB
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the email and password
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
$sql -> execute();
$count = $sql->rowCount();
$result = $sql -> fetch();
// Now use $result['rowname'];
$stmt = $conn_business->prepare("SELECT * FROM members WHERE email='".$email."'");
$stmt ->execute();
$act = $stmt -> fetch();
//if email exists
if($count > 0)
{
//compare the password
if(strcmp($result["password"],$pass)==0)
{
// check if activated
if($act["activated"] == "0")
{
echo "act"; //account is not activated yet
}
else
{
echo "yes"; //Logging in
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no"; //Passwords don't match
}
else
echo "no"; //Invalid Login
?>
And this is my old mysql script...
session_start();
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the username and password
$sql="SELECT email, password members WHERE email='".$email."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$sql2="SELECT * FROM members WHERE email='".$email."'";
$result2=mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$act = $row2['activated'];
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
// check if activated
if($act == "0")
{
echo "act";
}
else
{
echo "yes";
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no";
}
else
echo "no"; //Invalid Login
Does anybody know, what I have done wrong? It is an automatically script.. It is called through AJAX and return data based on 'no', 'yes' and 'act' that tells the AJAX/jQuery script what to do.. As I said - the mysql script is working, so please if anyone could tell me what I have done wrong with the PDO script..
EDIT:
when it returns the data to the jQuery script, this should happen:
if yes: start session, redirect to page2.php with session started.
else if act: write in a field that the account is not activated.
else: write that email and password didn't match.
The thing is, that when I try to write the correct e-mail and password - it continues to write : "email and password didn't match" instead of redirecting.. When I say that it is not working it is because the mysql script does as described but the PDO script doesn't..
And I have tried to change the 'echo "no";' to 'echo "yes";' to see if the login would start anyway, but somehow it continues to write that the email and password didn't match..
SOLUTION:
I ahven't told this because I thought it was unnecessary, but the reason for it not to work was because of that i have had my old mysql code in comment marks on top of the page, so that the session_start command didn't work.. After deleting the old code it worked, but then I found something else to change, and that is in the PDO script when it is validating it says:
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
and then I just changed the '-' after $sql to '=' and now, everything works perfectly... Anyhow thank you everybody.. hope this code can help others..
Did you even read the manual before you "started using" PDO?
That is not how prepared statements are supposed to be used! Your code is filled with SQL injections.
Why are you selecting same row twice ?
The strcmp() is not for checing if one string is identical to another.
And hashing passwords as simple MD5 is just a sick joke.
session_start();
//very stupid way to acquire connection
require_once("connect.php");
//get the posted values
$email = htmlspecialchars($_POST['email'],ENT_QUOTES);
if (filter_var( $email, FILTER_VALIDATE_EMAIL))
{
// posted value is not an email
}
// MD5 is not even remotely secure
$pass = md5($_POST['psw']);
$sql = 'SELECT email, password, activated FROM members WHERE email = :email';
$statement = $conn_business->prepare($sql);
$statement->bindParam(':email', $email, PDO::PARAM_STR);
$output = 'login error';
if ($statement->execute() && $row = $statement->fetch())
{
if ( $row['password'] === $pass )
{
// use account confirmed
if ( $row['activated'] !== 0 ) {
$output = 'not activated';
$_SESSION['email'] = $email;
}
$output = 'logged in';
}
}
echo $output;
i believe the second query in your scripts is not necessary you could simple do
SELECT * FROM members WHERE email=:EMAIL AND password=:PWS;
use bindParam method
$qCredentials->bindParam(":EMAIL",$EMAIL);
$qCredentials->bindParam(":PWS",$PWS);
then do more understable outputs rather than yes or no..
try "Unable to login: Invalid credentials supplied" for invalid types of values or "Unable to login: Invalid credentials, couldn't find user" for invalid user credentials.
You could try to start the session after the user has been successfully logged in your IF condition returning yes, and the methods
$PDOstatement->debugDumpParams()
$PDOstatement->errorInfo()
$PDOstatement->errorCode()
will help you understand what went wrong with a query!