I have created a registration form ( see code below ). There are two fields for the password, the second serving as a check and upon form submission I check if the input in the fields matches. If they don't a message is successfully sent that the passwords do not match but the new user record is still inserted into the database. How can I prevent record insertion if the password fields do no match?
Here is the code:
<?php
$username = isset( $_POST["username"] ) ? $_POST["username"] : "";
$password = isset( $_POST["password"] ) ? $_POST["password"] : "";
$confirm = isset( $_POST["confirm"] ) ? $_POST["confirm"] : "";
if( !empty( $username ) && !empty( $password ) ) {
if( $password != $confirm )
header( "location:registration.php?msg = Password does not be match." );
$host = "localhost";
$user = "i have put my username here";
$pass = "i have put my pass here";
$link = mysql_connect( $host,$user,$pass ) or die( mysql_error() );
mysql_select_db( "web_db",$link );
$query = "SELECT * FROM users WHERE username = '".mysql_escape_string( $username )."'";
$result = mysql_query( $query );
$count = mysql_num_rows( $result );
if( $count = = 1 ) {
header( "location:registration.php?msg = username already exists" );
} else {
$qry = "INSERT INTO users( username,password )VALUES( '".mysql_escape_string( $username )."', '".mysql_escape_string( $password )."' )";
mysql_query( $qry );
echo "You are successfully registered.";
}
mysql_close( $link );
} else {
header( "location:registration.php?msg = Username or password cannot be blank." );
}
Try this:
if($password != $confirm){
header("location:registration.php?msg=Password does not be match.");
exit;
}
else {
// rest of the code goes here
}
if ($password != $confirm) {
header("location:registration.php?msg=Password does not be match.");
exit();
}
Try using the above code it might help.
Related
I am struggling to get the login code to run successfully. It keeps on echoing the "Username or Password incorrect.." section, though the correct username and password in entered. Am I missing something somewhere, please help.
<?php
//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
$username = checkData($_POST['username']);
$password = checkData($_POST['password']);
require ('config.php'); //database connection
global $dbselect;
$qry = 'SELECT username, password
FROM users
WHERE username = :username AND password = :password
LIMIT 1';
$statement = $dbselect->prepare($qry);
$statement->bindValue(':username', $username);
$statement->bindValue(':password', $password);
$statement->execute();
$login = $statement->fetch(PDO::FETCH_ASSOC);
if (count($login) > 0 && password_verify($password, $login['password'])) {
$_SESSION['username'] = $login['username'];
header('location:home.html');
} else {
echo "Username or Password incorrect. Please try again.";
}
$statement->closeCursor();
}
//validate data
function checkData($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The following worked in test ( up to the password_verify where I used a different test as I have PHP 5.3.2 and hence no password_verify ) ~ hopefully it might prove of benefit.
<?php
session_start();
/* error messages used to display to user */
$ex=array(
0 => 'One or more required POST variables are not set',
1 => 'Both username & password are required',
2 => 'Failed to prepare SQL query',
3 => 'Query failed',
4 => 'No results',
5 => 'Invalid login details'
);
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
if( isset( $_POST['Submit'], $_POST['username'], $_POST['password'] ) ) {
$username = !empty( $_POST['username'] ) ? filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING ) : false;
$password = !empty( $_POST['password'] ) ? filter_input( INPUT_POST, 'password', FILTER_SANITIZE_STRING ) : false;
if( $username && $password ){
require('config.php');
global $dbselect;/* ??? */
/* use the username in the sql not password & username */
$sql='select `username`, `password`
from `users`
where `username` = :username';
$stmt=$dbselect->prepare( $sql );
/* only proceed if prepared statement succeeded */
if( $stmt ){
$stmt->bindParam( ':username', $username );
$status=$stmt->execute();
if( !$status )throw new Exception('',3);
$rows=$stmt->rowCount();
if( !$rows > 0 )throw new Exception('',4);
$result = $stmt->fetchObject();
$stmt->closeCursor();
/* password_verify is available from PHP 5.5 onwards ~ I have 5.3.2 :( */
if( $result && function_exists('password_verify') && password_verify( $password, $result->password ) ){
/* valid */
$_SESSION['username']=$username;
exit( header('Location: home.html') );
} else {
/* bogus - invalid credentials */
throw new Exception('',5);
}
} else {
/* sql prepared statement failed */
throw new Exception('',2);
}
} else {
/* either username or password was empty */
throw new Exception('',1);
}
} else {
/* one or more POST variables are not set */
throw new Exception('',0);
}
}catch( Exception $e ){
/* set a session variable to ensure error message is displayed only once */
$_SESSION['error']=$ex[ $e->getCode() ];
/* reload the login page with error code */
exit( header( 'Location: ?error=' . $e->getCode() ) );
}
}
?>
<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
<!-- the php/html login page -->
<form method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
<input type='submit' name='Submit' value='Login' />
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['error'], $_SESSION['error'] ) ){
unset( $_SESSION['error'] );
/* display the error message */
echo "<h2 style='color:red'>{$ex[ $_GET['error'] ]}</h2>";
}
?>
</form>
</body>
</html>
/**
* You might need to save a hashed copy of the password at the point of
* user creation, so that you can password_verify the input password against the hashed
* copy returned from the DB.
* something like this :
* $hashed = password_hash($password, PASSWORD_BCRYPT);
* NOTE : I've changed you code to an extent, pls adapt.
*/
//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
$username = checkData($username);
$password = checkData($password);
$dbname = "testo";
$servername = "localhost";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "root", "");
$parr = array($username,$password);
$qry = 'SELECT username, password, phashed
FROM users
WHERE username = ? AND password = ?
LIMIT 1';
$stmt = $conn->prepare($qry);
$Qres = $stmt->execute($parr);
$login = ($Qres) ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();
if (count($login) > 0 && password_verify($password, $login[0]['phashed'])) {
$_SESSION['username'] = $login[0]['username'];
header('location:home.html');
} else {
echo "Username or Password incorrect. Please try again.";
}
$conn = null;
}
//validate data
function checkData($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
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;
I am new at php and I followed some youtube video's to build a littel project.
I have a table of users:
id
username
email
password
and I'm trying to build a private message system. I want to get the id of the user that is now logged in. But when I write my_id = $_Session[ 'id' ] I get an error : "Undefined index: id" but when I write $my_id = $_SESSION['username'] I get the username with no error and it echo's me the username. What is the difference?
That is all the code:
<?php
session_start();
$db = mysqli_connect( "localhost", "root", "", "travelersdb" );
if( #$_SESSION[ "username" ] )
{
?>
<html>
<head>
<title>Home Page</title>
</head>
<?php
include( "header.php" );
echo "<center><h1>Private Message System</h1>";
include( "message_title_bar.php" );
if( isset( $_GET[ "user" ] ) && !empty( $_GET[ "user" ] ) )
{
?>
<form method = 'post' >
<?php
if( isset( $_POST[ "message"] ) && !empty( $_POST[ "message" ] ) )
{
$user=$_GET['user'];
$my_id = $_SESSION['username']; // ------> Doesn't work when changed to 'id'
$random_number = rand();
$sql_m = "SELECT 'hash'
FROM message_group
WHERE ( user_one = '" . $my_id . "' AND user_two = '" . $user . "' )
OR ( user_one = '" . $user . "' AND user_two = '" . $my_id . "' )";
$check_con = mysqli_query( $db, $sql_m );
$rows = mysqli_num_rows( $check_con );
if( $rows == 1 )
{
echo "<p>Conversation already started!</p>";
}
else
{
echo $user . "</br>";
echo $my_id; -------> Wanted to echo the $my_id to check...
echo $random_number;
// $sql_In = "INSERT INTO message_group( user_one, user_two, hash )
// VALUES( '1111', '2222', '2222' )";
// mysqli_query( $db, $sql_In );
echo "<p>Conversation Started</p>";
}
}
?>
Enter Message : </br>
<textarea name = 'message' rows = '7' cols = '60'>
</textarea>
<br></br>
<input type='submit' value="Send Message" />
</form>
<?php
}
else
{
echo "<b>select user</b>";
$sql = "Select id,username from users";
$check = mysqli_query($db,$sql);
while ( $run_user = mysqli_fetch_array( $check ) )
{
$user = $run_user[ 'id' ];
$username = $run_user[ 'username' ];
echo "<p><a href = 'send.php?user=$user'>$username</a></p>";
}
}
?>
</html>
<?php
}
else
{
echo "You must be logged in.";
}
?>
Update: done this but still is doesn't work. doesn't identify the id. this is the login.php:
<?php
session_start();
//connect to database
$db=mysqli_connect("localhost","root","","travelersdb");
if(isset($_POST['login_btn']))
{
//$username=mysql_real_escape_string($_POST['username']);
//$password=mysql_real_escape_string($_POST['password']);
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$password=md5($password); //Remember we hashed password before storing last time
$sql="SELECT * FROM users WHERE username='$username' AND password='$password'";
$result=mysqli_query($db,$sql);
if(mysqli_num_rows($result)==1)
{
$_SESSION['message']="You are now Loggged In";
$_SESSION['username']=$username;
$sql_t = "select id from users where username='$username' AND password='$password'";
$id = mysqli_query($db, $sql_t);
$_SESSION['id']=$id;
header("location:index.php");
}
else
{
$_SESSION['message']="Username and Password combiation incorrect";
}
}
?>
You may haven't set it to the session.
Use print_r($_SESSION); and check whether your index -> id is there or not.
$_SESSION index is like a variable name for your session value. If you haven't created this session/variable before, you can not retrieve its value because it is undefined
This is my code for registration part.
<?php
include_once('config.php');
$uname=mysql_real_escape_string($_POST["fname"]);
$email = mysql_real_escape_string( $_POST["email"] );
$phone=mysql_real_escape_string($_POST["phone"]);
$country = mysql_real_escape_string( $_POST["country"] );
$region = mysql_real_escape_string( $_POST["region"] );
$zip = mysql_real_escape_string($_POST["zip"]) ;
$upass = mysql_real_escape_string( md5($_POST["password"]) );
if( empty($uname) || empty($email) || empty($phone) || empty($country) || empty($region) || empty($zip) || empty($upass) )
{
echo "all fields are mandatory - from PHP!";
exit();
}
$res = mysql_query("SELECT email FROM registration WHERE email='$email'");
$row = mysql_num_rows($res);
if( $row > 0 ){
echo "email $email has already been taken";
}
else
{
$sql = mysql_query("INSERT INTO registration (fname,email,phone,country,region,zip,password)VALUES(
'$uname',
' $email',
'$phone',
'$country',
'$region',
'$zip',
'$upass' )");
if($sql){
echo "Inserted Successfully";
}
else
echo "Insertion Failed";
}
?>
this is my code for login php....
<?php
session_start();
include_once('config.php');
$email = mysql_real_escape_string( $_POST["email"] );
$password = mysql_real_escape_string( md5($_POST["password"]) );
if( empty($email) || empty($password) ){
echo "Email and Password Mandatory ";
}
else
{
$sql = mysql_query("SELECT fname FROM registration WHERE(
email='$email'
AND
password='$password')");
while($row = mysql_fetch_array($sql)){
$_SESSION['user_name'] = $row['fname'];
}
//$res = mysql_query($sql);
//$row = mysql_fetch_array($res);
if( $_SESSION['user_name']!= '' )
echo "<script>location.href='../index.php?con=1'</script>";
else
echo "Failed To Login";
}
?>
And it comes with a error after login...
Notice: Undefined index: user_name in C:\xampp\htdocs\cinderella\php\login.php on line 21
Failed To Login //
** Any lead for this issue is highly appreciable...Thank you **
Check your insert query, there is an whitespace within the $email field.
$sql = mysql_query("INSERT INTO registration (fname,email,phone,country,region,zip,password)VALUES(
'$uname',
WHITESPACE ------> ' $email',
'$phone',
'$country',`
Remove the space before the email in your INSERT query.
Secondly, I'd advice you to use num_rows before fetching to check if the user account exists. Try:
if(mysql_num_rows($sql) == 0) echo "Failed to login!";
else {
$fetch = mysql_fetch_array($sql);
$_SESSION['user_name'] = $fetch['fname'];
}
Also I'd advice you to use MySQLi. You can program this OO, so you'll have a better overview of it. You can also use prepared statements, transactions, ...
Testing for $_SESSION['user_name'] will produce that notice if that array key does not exist in $_SESSION (e.g. when you haven't logged in). Try changing:
if( $_SESSION['user_name']!= '' )
to
if (array_key_exists('user_name', $_SESSION))
Your whole code is fu***d up.
doing mysql_real_escape_string on md5($_POST["password"]) . much better if you were doing inverted.
using mysql query which has been removed. should have used mysqli
Assigning values to variables to be inserted with check.Could have made a check for isset($_POST['username']) && !empty($_POST['username'])
and, as mentioned by few others already a space in ' $email'
Would someone be able to give me a MySQL relation query for looking up a column value of a table based off of another value of the same table?
For instance, I have a table with 4 columns (id, name, email, password). How could I look up the the value of the "id" column of a certain user based off of their email in the "email" column and store the result (id) in a variable?
Here's the session() controller function
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] = 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password'] . 'chainfire db');
if (databaseContainsAuthor($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
$_SESSION['authorid'] = $author;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
unset($_SESSION['authorid']);
$GLOBALS['loginError'] =
'The specified email address or password was incorrect.';
return FALSE;
}
}
I've tried
SELECT id FROM article WHERE email='$email'
Is there a more efficient way to do it? I'm also not totally sure how to store the result of the query in the $author session variable.
Thanks in advance.
Your query is perfect (with the proviso that you are sanitising the $email variable - see the tale of Little Bobby Tables).
SELECT id FROM article WHERE email='$email'
And to perform that query and set the variable $author to the returned value is simply:
$author = 0;
if( ( $idFromEmail = #mysql_query( "SELECT id FROM article WHERE email='".mysql_real_escape_string( $email )."'" ) )
&& mysql_num_rows( $idFromEmail )==1
&& ( $r = mysql_fetch_assoc( $idFromEmail ) ) ){
$author = $r['id'];
}
Rewritten in long form, if the above is too complex to follow:
$author = 0;
if( !( $idFromEmail = #mysql_query( "SELECT id FROM article WHERE email='".mysql_real_escape_string( $email )."'" ) ){
// SQL Query Failed
}elseif( mysql_num_rows( $idFromEmail )!=1 ){
// More than, or less than, one row returned
}else{
$r = mysql_fetch_assoc( $idFromEmail );
$author = $r['id'];
}