I'm trying to create a "registration" form using php and mysql. The registration form asks for username and password. If any field is empty, it will let the user know which one. If the username is in use, it will also let the user know.
I know the connection to the database is ok, because I created a user that was I manually added into the database.
The strange thing is that my code is working in Cloud9. But, it wont work on a VM instance installed on google cloud.
In cloud9, it adds the user into the DB. In the google instance, it wont.
Can anyone check this and tell me what I;m doing wrong?
Thanks.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$display = $_POST['display'];
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root",NULL);
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if($stmt->rowCount() == 0 and $username != null and $password != null){
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
echo ("The user ".$username. " has been created.");
Try this, before all u need to check
if username and password is not empty because if username is empty i
cant make query valid to select username
check if username is in use
if username not in use, insert data into database
script
<?php
// error_reporting on
error_reporting(1);
ini_set('error_reporting', E_ALL);
$username = $_POST['username'];
$password = $_POST['password'];
// i commented $display variable because i don't see that u using it anywhere
//$display = $_POST['display'];
// database connection
$dbh = new PDO("mysql:host=localhost;dbname=mydb","root","");
// query
$stmt = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
// check if username and password is not empty
if ($username != '' && $password != '')
{
// check if username is in use
if($stmt->rowCount() > 1)
{
echo "Username in use, please choose another one.";
}
else
{
$insert = $dbh->prepare("INSERT INTO users(username,password) VALUES(:username, :password)");
$insert->bindParam(':username', $username);
$insert->bindParam(':password', $password);
$insert->execute();
// if last inserted id is true
if ($dbh->lastInsertId())
{
echo "The user ".$username. " has been created.";
}
else
{
echo "User not registered, please try again.";
}
}
}
else
{
echo "Please enter username and password.";
}
?>
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
Hey so I've followed a tutorial on how to create a functional registration system with php and all the code seems to work just fine, however the data I input in my registration form doesn't show up in my database even though the script gives me the output that I have successfully registered. Does anyone know a solution to this?
<?php
// Connect to the db
$DATABASE_HOST = 'localhost';
$DATABSE_USER = 'root';
$DATABSE_PASS = '';
$DATABSE_NAME = 'phplogin';
// Try to connect
$con = mysqli_connect($DATABASE_HOST, $DATABSE_USER, $DATABSE_PASS, $DATABSE_NAME);
if(mysqli_connect_errno()) {
//If there is an error stop the script and display the error
exit('Failed to connect to MySQL: '. mysqli_connect_error());
}
//check if the data already exists
if (!isset($_POST['username'], $_POST['password'], $_POST['email'])) {
//Could not get the data that should have been sent
exit('Please register first');
}
//Submitted registration values are not empty
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
//if empty exit the script
exit('Please complete the register form');
}
//check if the username has been used already
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
//encrypt password
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
//store the results to be able to check the db
if ($stmt->num_rows > 0) {
//username already exists
echo 'Username already used';
} else {
//Insert new account
if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
//hash the password and use password_verify
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['username'], $password, $POST['email']);
$stmt->execute();
echo 'You have succesfully registered, you can now login';
}}
$stmt->close();
} else {
//Something wrong with the sql statement
echo 'Could not prepare Statement!';
}
$con->close();
?>
It is very good practise to add error checking to your code when developing. An easy way to this is to add this at the top of your php page inside php code tags to at least echo errors out on your page -
error_reporting(E_ALL);
ini_set('display_errors', 1);
Your code should look like this, should return a record. If you had error reporting on, it would have told you where the errors are -
// Connect to the db
$DATABASE_HOST = 'localhost';
$DATABSE_USER = 'root';
$DATABSE_PASS = '';
$DATABSE_NAME = 'phplogin';
// Try to connect
$con = mysqli_connect($DATABASE_HOST, $DATABSE_USER, $DATABSE_PASS, $DATABSE_NAME);
if(mysqli_connect_errno()) {
//If there is an error stop the script and display the error
exit('Failed to connect to MySQL: '. mysqli_connect_error());
}
//check if the data already exists
if (!isset($_POST['username']) || !isset(['password']) || !isset($_POST['email'])) {
//Could not get the data that should have been sent
exit('Please register first');
} else {
//check if the username has been used already
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
//encrypt password
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
//username already exists
echo 'Username already used';
} else {
//Insert new account
if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
//hash the password and use password_verify
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['username'], $password, $POST['email']);
$stmt->execute();
echo 'You have succesfully registered, you can now login';
} else {
echo 'Data not inserted...';
}
}
$stmt->close();
}
$con->close();
I'm making a basic registration system with the help of a tutorial; the tutorial doesn't say how to make it so that it verifies if an email the user tried to register with has been taken, but it does so for the username. How do I make it so that it verifies both the username and email are free and not in the database? And yes, I did enter my database details properly, I just removed them for this post.
(By the way, this is a register.php file which the site goes to after entering details and pressing enter in another webpage.)
<?php
$DATABASE_HOST = '';
$DATABASE_USER = '';
$DATABASE_PASS = '';
$DATABASE_NAME = '';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
die ('Email is not valid!');
}
if (preg_match('/[A-Za-z0-9]+/', $_POST['username']) == 0) {
die ('Username is not valid!');
}
if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
die ('Password must be between 5 and 20 characters long!');
}
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo 'Username exists, please choose another!';
} else {
if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['username'], $password, $_POST['email']);
$stmt->execute();
echo 'You have successfully registered, you can now login!';
} else {
echo 'Could not prepare statement!';
}
}
$stmt->close();
} else {
echo 'Could not prepare statement!';
}
$con->close();
?>
Do it the same way you check if the username is already taken. Change your query to select id, password, email from accounts where username = ? or useremail = ?, make sure you add the email in bind_params and if it's already taken, you'll get a row.
Note that you won't be able to tell if the username is taken or if the email is. If you want to be able to tell, you may run two different queries, or compare results as follows.
Just fetch 1 row (limit 1) and if either the username or email address exists, notify the user. The code below should work.
$stmt = $con->prepare('select username, useremail from accounts where username = ? or useremail = ? limit 1');
$stmt->bind_param('ss', $_POST['username'], $_POST['useremail']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_name, $user_email);
$stmt->fetch();
$stmt->close();
if ($user_name == $_POST['username']) {
// Username is taken
} else if ($user_email == $_POST['useremail']) {
// Email is taken
} else {
// Email and username are both available
}
I am having issues getting some simple (or it seems simple) coding to cooperate. I've tried stripping it completely and typing everything out. Here is the code:
<?php
session_start();
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
$password = md5(trim($_POST['password']));
include('includes/admin.php');
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) == 0) {
echo '<p>Incorrect login.<br>Return to Login Page</p>';
} else {
$_SESSION['user'] = $username;
echo '<p>Login successful.<br>Go to Admin Page</p>';
}
}
?>
The goal is to have it redirect to the login page if unsuccessful and to redirect to another admin page if successful. I keep getting the "Incorrect Login" error, even when I type in the correct username and password.
Side Note: I know to redirect, I need to use header('Location: link.php'), it is not included for testing purposes.
If you didn't save your password as MD5 hash in your database you will never match it, cause in the line above you hash the password via MD5 before using in the query.
MD5 isn't secure! Use the PHP internal functions (password_hash(), password_verify()) to create and check passwords!
Use prepared statements!
Example code:
<?php
// Save a new user password in DB
$username = 'Max User';
$password = 'My_Secr3t_Pa5sw0rd';
$passwordHash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare("INSERT INTO `users` (`username`, `password`) VALUES(?, ?)");
$stmt->bind_param("ss", $username, $passwordHash);
$stmt->execute();
// Check user password
$stmt = $mysqli->prepare("SELECT `password` FROM `users` WHERE `username`=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (password_verify($password, $row['password']) {
echo "Password correct";
} else {
echo "Password incorrect!";
}
?>
I have a php(symphony) web application and an android application which access to the same database.The password field in the table is encrypted with symphony with Bcrypt and its value started with $2y$13,I used this code php to encrypt my password entered by the android application:
if(isset($_POST['password'])){
$password = $_POST['password'];
$pas_hash= password_hash("$password", PASSWORD_BCRYPT);
$sql = 'SELECT * FROM tbl_auth WHERE password = :pas_hash';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':pas_hash', $pas_hash, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount())
{
$result="true";
}
elseif(!$stmt->rowCount())
{
$result="false";
}
// send result back to android
echo $result;
}
The problem is that the value of pas_hash started with $2y$10 and when I used password_verify(), this function returns true result.
I didn't what's the problem because the final $result sent to my android application was false.
Thanks.
Okay, so if($stmt->rowCount()) is checking if the amount of rows is null or not, but it is not null, it is 0 because your result returned 0 rows.
Change your statement to if ($stmt->rowCount() > 0) and that should fix it.
Personally the way you are verifying your user(?) is a bit odd, it would be better to search the person's username, get their password from the database and use password_verify on the password you got from the user and the password you got from the database. This may not suit your functionality but it might aswell so take inspiration from the code below if you wish.
Example:
if(isset($_POST['username'])){
$username = $_POST['username'] // Or however you get the username.
$password = $_POST['password'];
$sql = 'SELECT * FROM tbl_auth WHERE username = :username';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if(password_verify($password, $result['password'])
{
$result="true";
}
else
{
$result="false";
}
// send result back to android
echo $result;
}
im trying to verify the users hashed password with their input but i cant get it working, so far it idenfities if theres a user with that username but it just wont verify the password. here is my code
<?php
$serverName = "localhost"; //Variables to access the user database
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database); //Connect to the database
if(!$conn){ //If the database failed to connect
die("Database failed to connect: " .mysqli_connect_error()); //Display an error message
}
$username = $_POST['username']; //set the username/ password varaibles
$password = $_POST['password'];
$hashPass = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password
$sql = "SELECT * FROM users WHERE username = ?"; //Select all usernames and passwords
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$count = mysqli_num_rows($result); //Count how many results there are
if ($count == 1)
{
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($password, $result )){
$count = 2;
}
}
if($count == 2) //If there is 1 account that matches
{
$stmt->close(); //Close the statment and connection
$conn->close();
session_start();
$_SESSION["LoggedUser"] = $username; //Log the user in
$_SESSION["lastPage"] = "login.php";
header("location: profile.php"); //Direct the user to their profile
}else //if there is no accounts that match
{
array_push($errors, "Username or password is incorrect");
session_start();
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php"; //Make this page the last page
header("location: index.php"); //Go to the homepage
}
?>
any help is appriciated, thanks
You are doing a lot of things you dont need to do.
A SELECT * will return all the columns so you dont need to do another SELECT for just the password.
Also you should not password_hash() the password again, when checking a password against the one already stored on the database. Use password_verify() and that will do all the checking. So you pass it the hashed_password from the database and the plain text password the user just entered on the screen, it will return true or false telling you if the password entered matched the hashed one on the database
<?php
// always do this early in the code
session_start();
$serverName = "localhost";
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database);
if(!$conn){
die("Database failed to connect: " .mysqli_connect_error());
}
// dont hash password again
//$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if(password_verify($_POST['password'], $row['password'] )){
// ----------------^^^^^^^^^^^^^^^^^^--^^^^^^^^^^^^^^^^
// Plain text pwd hashed pwd from db
$_SESSION["LoggedUser"] = $_POST['username'];
$_SESSION["lastPage"] = "login.php";
header("location: profile.php");
// put exit after a redirect as header() does not stop execution
exit;
}
} else {
$errors[] = "Username or password is incorrect";
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php";
header("location: index.php");
exit;
}
?>