Php, MySql And Webform - php

I have been trying to figure this out for over two days, I am following a youtube tutorial, with a basic sign in for my Android Application, but before I do that I want to test the .php script.
I am thinking that I should get a success when I press the login button but I am getting Invalid credentials, and I know that the username and password is correct
Below is my login.php script.
require("config.inc.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "SELECT id, username, passwrd
FROM application_users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
echo $row;
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
</form>
<?php
}
?>
So when the script loads and I input the values from the remote MYSQL server, the message comes back as invalid credentials.I just want to make sure my login is successful before I head over to the android part, which would be a big todo in itself.

I haven't had the opportunity to test it with a real database, but this should work. You still have to add the require("config.inc.php"); on the top of the file and I've added a custom database connection. I also work with PDO so the queries may look like different than what you've used so far.
<?php
// Database connection
try
{
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'myusername', 'mypassword');
$db->exec('SET CHARACTER SET UTF8');
}
catch (Exception $e)
{
//Message in case of error when connecting to the database
die('Erreur : ' . $e->getMessage());
}
// *** End database connection
$username = ""; // Initialize value in order to keep its value so the user can still see it in his form
if (isset($_POST['login'])) { // if the "login" button is pressed
$username = $_POST['username']; // retrieve username value from the form
$password = $_POST['password']; // retrieve password value from the form
/*
* If a username is unique then a way to do it is to count how many times
* the couple with this username and this password appears in our database.
*/
$query = $db->prepare("SELECT COUNT(*) userAmount ".
"FROM application_users ".
"WHERE username = $username ".
"AND password = $password;");
$query->execute();
$query->closeCursor();
$resultAmount = $query->fetch();
if ($resultAmount['userAmount'] == 0){ // If the couple username-password is unfound
$message = "Username or password unknown";
} else {
$message("Login successful");
}
}
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" value="<?php echo($username); ?>" />
<br/><br/>
Password:<br/>
<input type="password" name="password" placeholder="password" value="" />
<br/><br/>
<input type="submit" name="login" value="Login" />
Register
</form>

Related

how to implement token base form submission in php

i have been trying to create my own OOPs style register login system in php, i have implemented some security features like xss protection using htmlentites(), prepare method for SQLinjection protection and token based form submission for csrf protection(currently i am stuck implementing this functions in my code, getting "Invalid token" while submitting form data).
But I am not very sure it is good enough for secure site to produce for real live project or not. And i would like you to review my codes, Please help me to solve implementing token base form submission in my code and suggest me the way to improve my coding style in my current code.
This is my register.php page
<?php
//error_reporting(0);
session_start();
if(isset($_POST["submit"])){
include "Db_handlers.php";
$db = new DbHandler();
$res = $db->createUser($_POST["name"], $_POST["email"], $_POST["password"], $_POST["re-password"], $_POST['token']);
print_r($res);
/*if($res){
echo "test";
}
else {
echo $res;
}*/
}
$token = $_SESSION['token'] = md5(uniqid(mt_rand(),true));
?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<div class="field">
<label for="name">Name:</label>
<input type="text" name="name" value="" />
</div>
<div class="field">
<label for="email">Email:</label>
<input type="text" name="email" value="" />
</div>
<div class="field">
<label for="password">Password:</label>
<input type="password" name="password" value="" />
</div>
<div class="field">
<label for="repassword">Re-Password:</label>
<input type="password" name="re-password" value="" />
</div>
<input type="hidden" name="token" value="<?=$token;?>"/>
<input type="submit" name="submit" value="submit" />
</form>
This is my DB handler class
<?php
require 'functions.php';
class DbHandler {
private $conn;
public function __construct() {
try{
$this->conn = new PDO("mysql:host=127.0.0.1;dbname=task_manager", "root" , "");
// echo "Connected";
}
catch(PDOException $e){
//die($e->getMessage());
echo "Connection Failed: ".$e->getMessage();
}
}
public function createUser($name, $email, $password, $repassword, $utoken) {
// $error = array();
$error = '';
$required_fields = array($name, $email, $password, $repassword);
$fields = array_map('trim', $required_fields);
if (in_array(null, $fields)) {
$error = 'Fields marked with an asterisk are required';
}
else if($this->valid_token($utoken) == false){
$error = "Invalid Token...!!!";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = 'Please enter a valid email address !';
}
else if(strlen($password) < 6){
$error = "Password must be atleast 6 characters";
}
else if($password !== $repassword){
$error = "Password do n\' t match!!";
}
else{
$name = escape($name);
$email = escape($email);
$password_hash = escape($password);
// First check if user already existed in db
if (!$this->isUserExists($email)) {
// Generating password hash
$password_hash = password_hash($password, PASSWORD_DEFAULT, ['cost'=>12]);
// insert query
$stmt = $this->conn->prepare("INSERT INTO users(name, email, password_hash, status) values(:name, :email, :password_hash, 1)");
//$stmt->bind_param("ssss", $name, $email, $password_hash);
$result = $stmt->execute(array(':name' => $name,':email' => $email,':password_hash' => $password_hash));;
//$stmt->close();
// Check for successful insertion
if ($result) {
// User successfully inserted
return $result;
} else {
// Failed to create user
$error = "Failed to create user";
}
} else {
// User with same email already existed in the db
$error = "User already exists";
}
}
return $error;
}
private function isUserExists($email) {
$stmt = $this->conn->prepare("SELECT id from users WHERE email = :email");
//$stmt->bind_param("s", $email);
$stmt->execute(array(':email' => $email));
//$stmt->bind_result();
$num_rows = $stmt->rowCount();
//$stmt->close();
return $num_rows > 0;
}
public function valid_token($token){
if(!isset($_SESSION['token']) || $token != $_SESSION['token'])
return false;
}
}
Your code is really hard to read... You should indent it properly.
Back to your question. It seems, you just return false, if your token is incorrect, but your forget to return true, if it is correct. If your return nothing, you implicitly return null, which evaluates to false. I guess, your code works, if your change valid_token like this:
public function valid_token($token){
return isset($_SESSION['token']) && $token == $_SESSION['token'];
}

How to make a warning message if possible duplicate entry is added?

I have here the code for insertion using PDO and the insertion is working fine my problem is that how can i can determine if i inputted in the textbox the record that is already in the database,in my database ihave a column of ID, Firstname and Lastname, ID is auto increment,Firstname is set to unique and lastly is password set to varchar..what i want to happen is that when try to insert a record that is already in the database i want a warning message or maybe a alert message that tells me that "the record is already duplicate"..can somebody please help me with it?
here is the code
class.php
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
and here is index.php
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
if($crud->create($Firstname,$Lastname))
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Insertion Failed!'); </script>";
}
}
?>
<form method="POST" class="signin" action="" name="Add" target="iframe">
<fieldset class="textbox">
<label class="username">
<span>Username</span>
<input id="Firstname" name="Firstname" value="" type="text" placeholder="Username" required/>
</label>
<label class="password">
<span>Password</span>
<input id="Lastname" name="Lastname" value="" type="password" Placeholder="Password" required/>
</label>
<br />
<button id="submit" type="submit" name="btn-save">Save</button>
<button id="submit" type="reset" name="reset">Reset</button>
<br />
<br />
<hr>
</fieldset>
</form>
If you have the correct UNIQUE keys set in your database, PDO will already throw such a warning/error. You can easily try it yourself by inserting twice the same name
You should try to change your code to this, as this will throw the actual error. The correct function to call would be PDOStatement::errorInfo
Example code would be like this:
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
if (!$stmt->execute())
{
throw new Exception('Could not execute SQL statement: ' . var_export($stmt->errorInfo(), TRUE));
}
return true;
}
catch(Exception $e)
{
// Here you can filter on error messages and display a proper one.
return $e->getMessage();
}
}
In your index.php, change your PHP code to this:
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
$result = $crud->create($Firstname,$Lastname);
if($result === TRUE)
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert(" . $result . "); </script>";
}
}
An other, better, method would be to do a separate SELECT before you do the actual insert to see if the values you are trying to insert already exist.

How to use bcrypt for user data with PHP/MySQL/JSON

I'm currently developing an android application and using PHP/MySQL/JSON for the user registration and the login procedere. Now i want to use bcyrpt for hashing the user data. I am totally new to PHP and read a lot of tutorials for hashing, but i do not found any proper tutorial for my PHP skript which i can use.
I tried the password_hash() function, but it won't work.
Can you please give me advice how i can use bcrypt with my files.
Those are my PHP files:
LOGIN
<?php
require("config.inc.php");
if (!empty($_POST)) {
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$validated_info = false;
$row = $stmt->fetch();
if ($row) {
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
?>
<h1>Login</h1>
<form action="login.php" method="post">
Username:<br />
<input type="text" name="username" placeholder="username" />
<br /><br />
Password:<br />
<input type="password" name="password" placeholder="password" value="" />
<br /><br />
<input type="submit" value="Login" />
</form>
Register
<?php
}
?>
REGISTER
<?php
require("config.inc.php");
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$response["success"] = 0;
$response["message"] = "Please Enter Both a Username and Password.";
die(json_encode($response));
}
$query = " SELECT 1 FROM users WHERE username = :user";
$query_params = array(
':user' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row) {
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
$query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass ) ";
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
In your register script you should not store the password directly, instead call the password_hash() function and store its result:
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);
In the login script you can get the password-hash from the database as you did, but instead of comparing it with the entered password, you have to call the password_verify() function:
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $existingHashFromDb);

Login system wont login

So, I have the following code which is supposed to work as a login system. When I enter the details that are supposed to be entered, it still comes up with "Wrong details. Please try again". This is probably a stupid basic bug but I am not that fluent with PHP yet.
<?php
$dbc = mysqli_connect("hostaddress","user","pass") or
die("Could not connect to server". mysqli_connect_error());
mysqli_select_db($dbc, "dbname") or die("could not connect to the database");
//Check if the login form has been submitted;
if(isset($_POST["go"])) {
$addr = mysqli_real_escape_string($dbc, htmlentities($_POST["e_address"]));
$psw = SHA1 ($_POST["u_pass"]); //Using sha1() to encrypt passwords
//query to check if the email address and password match;
$q = "SELECT * FROM users WHERE address='$addr' AND pass='$psw'";
//run the query and store result;
$res = mysqli_query($dbc, $q);
//Make sure we have a positive result;
if($res = mysqli_query($dbc, $q)) {
//Start a session;
session_start();
//Creating a log session variable that will persist through pages;
$_SESSION["log"] = "in";
//Redirecting to restricted page;
header("location: restricted.php");
} else {
//Create an error message;
$error = "Wrong details. Please try again";
}
} //End isset go
?>
<form method="post" action="#">
<p><label for="e_address">Email Address:</label></p>
<p><input type="text" name="e_address" value="" placeholder="Email Address" maxlength="30"></p>
<p><label for="u_pass">Password:</label></p>
<p><input type="password" name="u_pass" value="" placeholder="Password" maxlength="12"></p>
<p><button type="submit" name="go">Log me in</button></p>
</form>
<!-- Error Displayer -->
<p><strong><?php if(isset($error)) { echo $error; } ?></strong></p>
try to start with session_start(); at first line
and try add after the query or die(__LINE__." ".mysqli_error($dbc))
and U can use the query without the password and check the password then with php

login form needs to be completed a number of times before it logs in

I have a login form (HTML -> PHP). I enter the correct details, it then reloads the page and i have to enter the details again. I press submit and then it does it again. On the third time (sometimes the second I think) it actually logs me in.
Any help would be greatly appreciated.
Here is the forms HTML:
<!-- Login Form -->
<form method="post" id="login-form-splash">
<input type="text" class="text" name="username" onfocus="if(this.value == 'Username') { this.value = ''; }" value="Username" />
<input type="password" name="password" class="password" onfocus="if(this.value == 'Password') { this.value = ''; }" value="Password" />
<input type="submit" name="submit" value="Login" class="submit" />
<br />
<span>Lost Password?</span>
<br />
No account yet? Register.<br />
</form>
And here is the PHP actually doing the login:
<?php
//Check if login form was submitted.
if(isset($_POST['submit']))
{
//include important settings and functions.
include($_SERVER['DOCUMENT_ROOT'] . '/includes/config.php');
//Check if both fields were completed.
if($_POST['username'] == '' || $_POST['password'] == '')
{
//Tell them whats wrong.
echo "<script language=\"javascript\">alert('You need to complete both fields.');</script>";
} else
{
//The completed both fields.
//Localise vars.
$username = $_POST['username'];
$password = $_POST['password'];
//Protect against SQL Injection using mysql_prep function. [mysql_prep can be found in ./includes/functions.php]
mysql_prep($username);
mysql_prep($password);
//MD5 Hash the password to check against hashed password in DB.
$password = md5($password);
//Connect to MySQL Database.
include($_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php');
//If connection exists
if(isset($mysql_connection))
{
//Run MySQL Query on DB.
$sql = "SELECT * FROM `users` WHERE `username` = '$username' AND `password` = '$password'";
$result = mysql_query($sql, $mysql_connection) or die('Cannot Execute:'. mysql_error());
//Check if there is a match. There can only be one.
if(mysql_num_rows($result) == 1)
{
//Create session variables and set values within them.
$_SESSION['username'] = $username;
//Redirect to Members page.
header('Location: members.php');
} else
{
//Username and Password are not correct, or the account doesn't exist.
echo "<script language=\"javascript\">alert('Please check that you have entered the details correctly.');</script>";
}
} else
{
//Database error.
echo "<script language=\"javascript\">alert('There was a database error. Please try again or contact a technician at errors#eatgamesleep.com');</script>";
}
}
}
?>
Maybe you should replace
if(isset($mysql_connection)) {
to just
if($mysql_connection){

Categories