This question already has answers here:
Check if email already exists in database
(4 answers)
Closed 6 years ago.
How do I check if the email already exist in the database and deny the registration?
MySQL was the one taught to me and I'm currently on a wall using MySQLi.
Here is the code that I'm currently working on using MySQLi:
<?php
$cookie_name = "loggedin";
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarcaps";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Database connection failed: ".mysqli_connect_error());
}
if (isset($_POST['login']))
{
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
$cookie_value = $user;
setcookie($cookie_name, $cookie_value, time() + (180), "/");
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if (isset($_POST['register']))
{
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$phash = sha1(sha1($pass."salt")."salt");
$sql = "INSERT INTO users (id, email, username, password) VALUES ('','$email', '$user', '$phash');";
$result = mysqli_query($conn, $sql);
}
?>
Despite using mysqli your code is still vulnerable to sql injection as you directly embed variables in the sql statements - use prepared statements to avoid nasty surprises. The following is not tested but should show how you can use prepared statements. There are better ways of hashing the password - such as password_hash and also password_verify though these are not available in PHP versions prior to 5.5
$response=array();
$cookie_name='loggedin';
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = '';
$dbname = 'scholarcaps';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
if( isset( $_POST['login'] ) ) {
$user = $_POST['username'];
$pass = $_POST['password'];
$phash = sha1( sha1( $pass . "salt" ) . "salt" );
$sql='select `username`, `password` from `users` where `username`=? and `password`=?';
$stmt=$db->prepare( $sql );
if( $stmt ){
$stmt->bind_param( 'ss', $username, $phash );
$result=$stmt->execute();
if( !$result ) $response[]='Query failed';
$stmt->store_result();
$stmt->bind_result( $name, $pwd );
$stmt->fetch();
if( $stmt->num_rows()==0 ) $response[]='No such user';
else {
$stmt->free_result();
$stmt->close();
$db->close();
setcookie( $cookie_name, $user, time() + 180, "/" );
exit( header( "Location: personal.php" ) );
}
$stmt->free_result();
$stmt->close();
$db->close();
/* show errors */
if( !empty( $response ) ){
echo '<ul><li>',implode('</li><li>',$response),'</li></ul>';
}
}
} elseif( $_POST['register'] ){
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$phash = sha1( sha1( $pass . "salt" ) . "salt" );
/* Does the email address already exist? */
$emailfound=false;
$sql='select `email` from `users` where `email`=?';
$stmt=$db->prepare( $sql );
if( $stmt ){
$stmt->bind_param('s',$email);
$result=$stmt->execute();
if( $result ){
$stmt->store_result();
$stmt->bind_result( $emailfound );
$stmt->fetch();
$stmt->free_result();
}
}
if( $emailfound ){
echo 'Sorry, that email address already exists in our database. Please try again with a different address.';
$stmt->close();
$db->close();
} else {
/* the `id` should be automatically generated I assume - hence being omitted here */
$sql='insert into `users` (`email`, `username`, `password`) values (?,?,?);';
$stmt=$db->prepare( $sql );
if( $stmt ){
$stmt->bind_param( 'sss', $email, $username, $phash );
$result=$stmt->execute();
$stmt->free_result();
$stmt->close();
$db->close();
if( $result ) header('Location: login.php');
else{
/* failed to register the user */
}
}
}
}
I solved this problem by setting my email column with unique attribute. After the registration submit you can catch the mysqli_errno(). So you will see if there is a duplicate entry.
You will save a check-query with this solution.
If you don't want to match the email, you just want to make sure an email address exists, you could...
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash' AND email<>'';";
or, to specify a minimum length...
$sql = "SELECT * FROM users WHERE username='$user' AND password='$phash' AND LEN(email) > 0;";
Use this php function for get record count in db
$count=mysqli_num_rows($result)
after check it more than 0 or not
Try this,
add this code after sha1
$result = mysql_query("select COUNT(id) from users where email='".$email."'");
$count = mysqli_num_rows($result);
if($count > 0){
echo "email exist";
}else
{
$sql = "INSERT INTO users (id, email, username, password) VALUES ('','$email', '$user', '$phash');";
$result = mysqli_query($conn, $sql);
}
Related
I'm creating a back end to my website and running into issues with the login user part.
The user registration into the database is made with the password_hash function using the code below:
UserReg.php :
<?php
require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);
if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}
$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);
add_user($mysqli,$username, $token);
function add_user($mysqli,$username, $token) {
$query = $mysqli->prepare("INSERT INTO users(username, password) VALUES
(?,?)");
$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();
if(!$result) {
die($mysqli->error);
}
$query->close();
}
My login form skips to a blank page even when i insert my username and password. Doesn't even go to the login error message.
Login.php
<?php
include 'db.php';
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->bind_result($pass);
while ($result = $stmt->num_rows()) {
if($stmt->password_verify($pwd, $result)) {
echo "Your username or password is incorrect";
} else {
header("Location: Menu.php");
}
}
What am i missing?
Appreciate your help.
I think you need to take a look at password_verify how it works.
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT username, password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if ($stmt->num_rows == 1) { //To check if the row exists
if ($stmt->fetch()) { //fetching the contents of the row
if (password_verify($pwd, $password)) {
$_SESSION['username'] = $username;
echo 'Success!';
exit();
} else {
echo "INVALID PASSWORD!";
}
}
} else {
echo "INVALID USERNAME";
}
$stmt->close();
How to get the value of the column 'ProfilePicture' for the current user (which is stored in a session) from a database and save it into a variable?
Here is an example of a possible structure for the query:
if($email="iahmedwael#gmail.com" show 'ProfilePicture' value for that username) //declare a variable to save the value of ProfilePicture
<?php
$posted = true;
if (isset($_REQUEST['attempt'])) {
$link = mysqli_connect("localhost", "root", "", 'new1') or die('cant connect to database');
$email = mysqli_escape_string($link, $_POST['email']);
$password = mysqli_escape_string($link, $_POST['Password']);
$query = mysqli_query($link, " SELECT *
FROM 360tery
WHERE Email='$email'
OR Username= '$email'
AND Password='$password' "
) or die(mysql_error());
$total = mysqli_num_rows($query);
if ($total > 0) {
session_start();
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
} else {
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
For security purposes, it's my recommendation that you use PDO for all your database connections and queries to prevent SQL Injection.
I have changed your code into PDO. It should also get the value from the column ProfilePicture for the current user and save it to the variable $picture
Note: you will need to enter your database, name and password for the database connection.
Login Page
<?php
session_start();
$posted = true;
if(isset($_POST['attempt'])) {
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$email = $_POST['email'];
$password = $_POST['Password'];
$stmt = $con->prepare("SELECT * FROM 360tery WHERE Email=:email OR Username=:email");
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
if(password_verify($password, $row['Password'])) {
$_SESSION['email'] = $email;
header('location: /html/updatedtimeline.html');
}else{
echo "<script type='text/javascript'>alert('Wrong username or Password!'); window.location.href='../html/mainpage.html';</script>";
}
}
}
?>
User Page
<?php
session_start();
$con = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pass');
$stmt = $con->prepare("SELECT ProfilePicture FROM 360tery WHERE username=:email OR Email=:email");
$stmt->bindParam(':email', $_SESSION['email']);
$stmt->execute();
if($stmt->rowCount() > 0) {
$row = $stmt->fetch();
$picture = $row['ProfilePicture'];
}
?>
Please let me know if you find any errors in the code or it doesn't work as planned.
I am trying to make login script safe to stop hacking of my website. I am trying to use mysql_real_escape_string in my script can anyone guide me if i am wrong in this.
Here is my code
<?php
session_start();
include("lib/conn.php");
?>
<?php
$email=$_POST['user'];
$password=$_POST['password'];
if ($email && $password){
$query = "SELECT * FROM register WHERE email = '$email' AND password= '$password' and status = '1'";
mysql_real_escape_string($email);
mysql_real_escape_string($password);
$result = mysql_query( $query ) or die ("didn't query");
$num = mysql_num_rows( $result );
if ($num == 1){
$_SESSION['ocer']=$email;
header("Location: admin.php");
}
else {
header("Location: index.php?l=1");
}
}
?>
1.- Don't use mysql* functions because are deprecated, use mysqli_* functions or PDO
2.- You should use prepared statements, this is an example using mysqli_* functions:
<?php
$email=$_POST['user'];
$password=$_POST['password'];
if ($email && $password){
$query = "SELECT email, password
FROM register
WHERE email = ?
AND password= ?
AND status = '1'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $email, $password);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $column1, $column2);
while (mysqli_stmt_fetch($stmt)) {
echo "Column1: {$column1}, Column2: {$column2}";
}
?>
First of all. Use PDO with bind parameter. Then you don't have to worry about injections.
mysql_real_escape_string returns the escaped string and should be used before constructing your query. Use is as so:
$password = mysql_real_escape_string($password);
Also. Don not retrieve by password and email. retrieve password by email and validate that there the same.
Hope it helps
Here is the example:
session_start();
include("lib/conn.php");
//using isset to avoid warnings.
$email = isset($_POST['user']) ? $_POST['user'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
//check if values are not null
if ($email !== null && $password !== null){
//escape email
$email = mysql_real_escape_string($email);
//retrieve password by email and limit 1 result
$query = "SELECT password FROM register WHERE email = '{$email}' and status = '1' LIMIT 1";
//run query
$result = mysql_query( $query ) or die ("didn't query");
//validate if query run correctly
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
//fetch row
$row = mysql_fetch_row($result);
//validate result
if ($row['password'] == $password){
$_SESSION['ocer']=$email;
header("Location: admin.php");
} else {
header("Location: index.php?l=1");
}
}
when the user enters their details they click on login but its not working, my connection to the database is fine its this file that is not working, any help would be appreciated, thanks
include '../connection.php'; //used to include connection file that is 1 level higher in the directory
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$fquery = 'SELECT Username FROM login LIMIT 0, 30 ';
$squery = 'SELECT Password FROM login LIMIT 0, 30 ';
$username_query = mysqli_query($dbc, $fquery);
$password_query = mysqli_query($dbc, $squery);
$username_row = mysqli_fetch_array($username_query);
$password_row = mysqli_fetch_array($password_query);
if($username == $username_row && $password == $password_row) {
echo 'username and password correct';
}
?>
<?php
include '../connection.php'; //used to include connection file that is 1 level higher in the directory
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$query = 'SELECT Username FROM login WHERE Username = ? AND Password = ?';
/* set a default value to check against */
$valid_user = '';
/* use prepared statement */
$stmt = mysqli_stmt_init($dbc);
if (mysqli_stmt_prepare($stmt, $query)) {
/* set question marks equal to values */
mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
mysqli_stmt_execute($stmt);
/* get the valid username only if query is successful */
mysqli_stmt_bind_result($stmt, $valid_user);
mysqli_stmt_fetch($stmt);
/* close the statment */
mysqli_stmt_close($stmt);
}
/* check if default was overwritten */
if($valid_user != '') {
echo 'username and password correct';
}
?>
Try this out, should accomplish what you are trying to do.
$username_query = mysqli_query($dbc, $fquery);
$password_query = mysqli_query($dbc, $squery);
$username_row = $username_query->fetch_array(MYSQLI_ASSOC);
$password_row = $password_query->fetch_array(MYSQLI_ASSOC);
if($username == $username_row['username'] && $password == $password_row['Password']) {
echo 'username and password correct';
}
$username = mysqli_real_escape_string($dbc, $_REQUEST['username']);
$password = mysqli_real_escape_string($dbc, $_REQUEST['password']);
$query = "SELECT * FROM login WHERE Username = '$username' AND Password = '$password' LIMIT 1";
if(mysqli_num_rows($query) > 0)
echo 'username and password correct';
I've written a functional login script using MySQL. However, I've now been told that it needs to be done using PDO, and I've a functional PDO connection:
function getConnection()
{
$userName = '*****';
$password = '*****';
$dbname = '******';
$db = new PDO("mysql:host=localhost;dbname=$dbname", $userName, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
However I've no idea how to convert the login query to PDO.
if (isset($_REQUEST['attempt']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$qry = mysql_query
("SELECT *
FROM subscriber
WHERE email = '$user'
AND password = '$password'")
or die(mysql_error());
$total = mysql_num_rows($qry);
if ($total > 0)
{
session_start();
$_SESSION['user'] = 'yes';
header('location: account.php');
exit;
}
else
{
// Do nothing.
}
}
How can I do it?
To get you started:
$db = getConnection();
$stmt = $db->prepare("
SELECT * FROM subscriber WHERE email = :email AND password = :password
");
$stmt->bindParam(":email" , $user );
$stmt->bindParam(":password", $password);
$stmt->execute();
$total = $stmt->rowCount();
Non-bloated version:
$stm = $pdo->prepare("SELECT * FROM subscriber WHERE email = ? AND password = ?");
$stm-> execute($_POST['user'], $_POST['password']);
if ($id = $stm->fetchColumn()) {
session_start();
$_SESSION['user'] = $id;
header('location: account.php');
exit;
}
You can also use this example if you would not like to use bindParam. But I extracted it from #eggyal's answer. Great thanks go to eggyal.
<?php session_start();
include_once('pdo.inc.php');
$username = (isset($_POST['username']))? trim($_POST['username']): '';
$password = (isset($_POST['password']))? $_POST['password'] : '';
$pas = md5($password);
$redirect = (isset($_REQUEST['redirect']))? $_REQUEST['redirect'] :
'view.php';
$query = ("SELECT username FROM site_user WHERE username=:username
AND password =:password");
$query_login = $con->prepare($query);
$query_login->execute(array(
':username'=>$username,
':password'=>$pas));
$result = $query_login->rowCount();
if($result>0)
{
$_SESSION['username'] = $username;
$_SESSION['logged'] = 1;
echo "success";
}
else {
// Set these explicitly just to make sure
echo 'User name invalid';
}
?>