I am sending to me a email when a new User has sign-up to aprove it. Now I have this verify.php Code:
<?php
mysql_connect("localhost", "database", "pw", "databasename") or die(mysql_error()); // Connect to database server(localhost) with username and password.
mysql_select_db("databasename") or die(mysql_error()); // Select registration database.
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
// Verify data
$email = mysql_escape_string($_GET['email']); // Set email variable
$hash = mysql_escape_string($_GET['hash']); // Set hash variable
$search = mysql_query("SELECT email, hash, active FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
// We have a match, activate the account
mysql_query("UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysql_error());
echo '<div class="statusmsg">Your account has been activated, you can now login</div>';
}else{
// No match -> invalid url or account has already been activated.
echo '<div class="statusmsg">The url is either invalid or you already have activated your account.</div>';
}
}else{
// Invalid approach
echo '<div class="statusmsg">Invalid approach, please use the link that has been send to your email.</div>';
}
?>
I get everything.. the mail with correct link:
http://www.yourwebsite.com/verify.php?email='.$email.'&hash='.$hash.'
But once I click the link it just stays in blank Website.. No error but no Change to... :(... Pretty sure there is small error I cant find..
Solved with:
<?php
ini_set('display_errors', true); error_reporting(E_ALL);
$link = $link = mysqli_connect("localhost", "database", "pw!", "database");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
// Verify data
$email = mysqli_escape_string($link, $_GET['email']); // Set email variable
$hash = mysqli_escape_string($link, $_GET['hash']); // Set hash variable
$passwort = mysqli_escape_string($link, $_GET['passwort']); // Set hash variable
$passwort_hash = password_hash($passwort, PASSWORD_DEFAULT);
$search = mysqli_query($link, "SELECT email, hash, active, passwort FROM users WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysqli_error());
$match = mysqli_num_rows($search);
if($match > 0){
// We have a match, activate the account
mysqli_query($link, "UPDATE users SET active='1' WHERE email='".$email."' AND hash='".$hash."' AND active='0'") or die(mysqli_error());
echo '<div class="statusmsg">Your account has been activated, you can now login</div>';
}else{
// No match -> invalid url or account has already been activated.
echo '<div class="statusmsg">The url is either invalid or you already have activated your account.</div>';
}
}else{
// Invalid approach
echo '<div class="statusmsg">Invalid approach, please use the link that has been send to your email.</div>';
}
?>
Check this line:
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
You have used "AND" here. It should be:
if((isset($_GET['email']) && !empty($_GET['email'])) && (isset($_GET['hash']) && !empty($_GET['hash']))){
I have checked your script, It is working with some modifications. Possible error according to me is status datatype. it should be 'int' Please check below.:
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
// Verify data
$email = mysql_escape_string($_GET['email']); // Set email variable
$hash = mysql_escape_string($_GET['hash']); // Set hash variable
$search = mysql_query("SELECT * FROM test_users WHERE u_email='".$email."' AND u_hash='".$hash."' ") or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
// We have a match, activate the account
mysql_query("UPDATE test_users SET u_status='1' WHERE u_email='".$email."' AND u_hash='".$hash."'") or die(mysql_error());
echo '<div class="statusmsg">Your account has been activated, you can now login</div>';
}else{
// No match -> invalid url or account has already been activated.
echo '<div class="statusmsg">The url is either invalid or you already have activated your account.</div>';
}
}else{
// Invalid approach
echo '<div class="statusmsg">Invalid approach, please use the link that has been send to your email.</div>';
}
?>
It's a bad idea to use die(), if this happens the error is logged to the Apache error log and you are left with a blank screen. You should consider moving away from using this way of interacting with mysql and consider using PDO (https://phpdelusions.net/pdo) with prepared statements.
To see what the actual error is follow your web server error log and see what is being logged.
Related
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.
I am trying to use the below code to create a login form. The problem being after registration when I am trying to login, getting an error message "Username or Password don't match" even though email & password are correct. I tried "$num <=1" and allows me to log in but obviously it is not authenticating the login details in that case. Any help will be appreciated.Most importantly this code is working fine on a local server like XAMPP but problem starts when using a host server like hostgator (no issue to connect with the server).
<?php
session_start(); // Starting Session
#Database connection
include('../config/connection.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit']))
{
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = '<p class="alert alert-danger">One or either field is missing</p>';
}
else
{
// Define $username and $password
$email=$_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection for Security purpose
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
// SQL query to fetch information of registerd users and finds user match.
$q = "SELECT * FROM users WHERE email = '$email' AND password = md5(SHA1('$password'))";
$r = mysqli_query($dbc, $q)or die(mysqli_error());
$num = mysqli_num_rows($r);
if($num ==1){
$_SESSION['username'] = $email;
header('Location:Index.php');
} else {
$error = '<p class="alert alert-danger">Username or Password don\'t match</p>';
}
mysqli_close($dbc); // Closing Connection
}
}
?>
in your query the $password should not be between the quotes, cause then it will seek for the string instead of the value of the variable.
$q = "SELECT * FROM users WHERE email = '$email' AND password = 'md5(SHA1($password))'";
make sure your password is hashed in your database
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!
I want to check which one of the username or password is incorrect in a single mysql query.
Scenario:
When a user types a username and password and clicks submit, I want to show an error message which one is incorrect. I need a simple and optimized query for this.
As a general rule of thumb I would say it's better return a message back to the user saying that "The username or password is incorrect" as it wouldn't indicate to an attacker if the username or password was wrong.
That's a nice way for an attacker to find valid usernames.
To answer your question, I think you'd have to do
SELECT username, password WHERE username=? OR password=?
and then go through the results with the given username and password, to find the right one.
$query = <<<EOL
SELECT IF(password = '$password', 1, 0)
FROM users
WHERE username='$username'
EOL;
$result = mysql_query($query)
if (mysql_numrows($result) == 0) then
echo 'Bad username';
} else {
$row = mysql_fetch_array($result);
if ($row[0] == 0) then
echo 'Bad password';
}
}
Of course, this assumes $username and $password have been properly escaped, and that $password has been massaged into whatever hash/encryption method you're using to store it in the DB.
Please use HTMl form with POST method the use following code::
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("My_TABLE_NAME", $con);
$Username = $_POST['Username']; // get username
$Password = $_POST['Password'] ; // get pwd
$sql="SELECT Username FROM My_TABLE_NAME WHERE Username=’".$Username.”’ and Password=’”.$Password.”’”;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
exit();
}
if(mysql_affected_rows()==0){
print "no such login in the system. please try again.";
exit();
}
else{
print "successfully logged into system.";
//proceed to perform website’s functionality – e.g. present information to the user
}
?>
Hey This is my login script, using PHP5 and MYSQLi, I just had help spotting errors in my query, but still it will not let me login, even though the username and password are correct and in the database, it just keeps returning the error: your username and password do not match any in our db. But I know they do lol...could any body spot the problem?
//Check if the form has been submitted
if (isset($_POST['login']))
{
//Check if username and password are empty
if ($_POST['username']!='' && $_POST['password']!='')
{
//Create query to check username and password to database
$validate_user = $mysqli->query('SELECT id, username, password, active FROM users WHERE = username = "'.$mysqli->real_escape_string($_POST['username']).'" AND password = "'.$mysqli->real_escape_string(md5($_POST['password'])).'"');
//We check if the query returns true
if ($validate_user->num_rows == 1)
{
$row = $validate_user->fetch_assoc();
//Check if the user has activated there account
if ($row['activated'] == 1)
{
$_SESSION['id'] = $row['id'];
$_SESSION['logged_in'] = true;
Header('Location: ../main/index.php');
}
//Show this error if activation returns as 0
else {
$error = '<p class="error">Please activate your account.</p>';
}
}
//Show this error if the details matched any in the db
else {
$error = '<p class="error">Your username and password are not in our database!</p>';
}
}
//Show this error if the username and password field have not been entered
else {
$error = '<p class="error">Please enter your username and password.</p>';
}
}
Instead of
SELECT ... FROM users WHERE = username = ...
It should be
SELECT ... FROM users WHERE username = ...
If you keep getting problems like this, try storing the query in a variable and echo it, so you can copy-paste it into your database management tool and see if there are any query errors.
To make it most reliable way, I'd suggest to trigger this error according to main error handling settings:
//just in sake of readability
$user = $mysqli->real_escape_string($_POST['username']);
$pass = $mysqli->real_escape_string(md5($_POST['password']));
$sql = "SELECT id, username, password, active FROM users
WHERE username = '$user' AND password = '$pass'";
$res = $mysqli->query($sql) or trigger_error(mysqli->error.$sql);
note that trigger_error function. it will bring error message to the standard error output. On the development PC it will be browser's screen or a log file on the production server.