PHP and Swift : Fatal error on password_hash() - php

I have set up my sign up and sign in php files they're on the server and it works with my swift app. I can sign in and sign up easily. But when i added the password_hash() method to had security to the user password it gives an error on Xcode when I try to sign up. Is there any other way to have a store the password securely if this doesn't work anymore. Yes I have php 5.5.34 installed:
error via Xcode:
DATA: <br />
<b>Fatal error</b>: Call to undefined function password_hash() in <b>/*/*/public_html/*/signup.php</b> on line <b>92</b><br />
signup.php
// Hash password and insert new user to table
$hashPassword = password_hash($password, PASSWORD_DEFAULT);
$command = " INSERT INTO USER
(firstname, lastname, username, email, password)
VALUES
('$firstname', '$lastname', '$username', '$email', '$hashPassword')";
if ( mysqli_query($DB, $command) ) {
// Search for newUser
$command = "SELECT * FROM USER WHERE username = '$username'";
$sql = mysqli_query($DB, $command);
if ( mysqli_num_rows($sql) != 0 ) {
$newUser = mysqli_fetch_array($sql);
$returnData["status"] = "200";
$returnData["message"] = "Success!";
$returnData["ID"] = $newUser["ID"];
$returnData["firstname"] = $newUser["firstname"];
$returnData["lastname"] = $newUser["lastname"];
$returnData["username"] = $newUser["username"];
$returnData["email"] = $newUser["email"];
}
echo json_encode($returnData);
return;
} else {
$returnData["status"] = "400";
$returnData["message"] = "Sorry, something must've went wrong. Please try again...";
echo json_encode($returnData);
return;
}
signin.php
// Find user from table and sign in
$command = "SELECT * FROM USER WHERE email = '$email'";
$sql = mysqli_fetch_array( mysqli_query($DB, $command) );
if ( isset($sql) ) {
$hashPassword = $sql["password"];
if ( password_verify($password, $hashPassword) ) {
$returnData["status"] = "200";
$returnData["message"] = "Success!";
$returnData["ID"] = $sql["ID"];
$returnData["username"] = $sql["username"];
}
echo json_encode($returnData);
return;
} else {
$returnData["status"] = "400";
$returnData["message"] = "Sorry, something must've went wrong. Please try again...";
echo json_encode($returnData);
return;
}

You can use this library to get the password_*() functions. Also provides < PHP 5.5 support.

Related

Php login script with login attemp

How can i limit the failed logins with this script? If the login fails, i insert it into the sql. (Is it the right way?)
But how can i check at the next login, that the user can now log in? I would take the login limit in 1 hour.
Aniway, is this code is good for that?
<?php
$loginError = array();
if(isset($_POST['login_submit']))
{
if(empty($_POST['email']) or !isset($_POST['email'])){$loginError[] = "Hiányzó email cím.";}
if(empty($_POST['pass']) or !isset($_POST['pass'])){$loginError[] = "Hiányzó jelszó.";}
if(strlen($_POST['email']) > 50 ){$loginError[] = "Hibás adat az email mezőben.";}
if(strlen($_POST['pass']) > 40 ){$loginError[] = "Hibás adat a jelszó mezőben.";}
if(count($loginError) == 0 )
{
$email = mysqli_real_escape_string($kapcs,$_POST['email']);
$pass = sha1($_POST['pass']);
$lekerdezes = mysqli_query($kapcs, "SELECT * FROM admin_user WHERE email = '$email'") or die(mysqli_error($kapcs));
if(mysqli_num_rows($lekerdezes) > 0 )
{
$adat = mysqli_fetch_assoc($lekerdezes);
if($adat['status'] == 1 )
{
if($adat['pass'] == $pass)
{
$_SESSION['adatok'] = $adat;
$_SESSION['email'] = $adat['email'];
$_SESSION['userid'] = $adat['id'];
header("Location:home.php");
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Még nincs aktiválva a fiók.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
}
?>
I would create a field in the database called status (blocked/ok) and assuming youve got a field timestamp for the last login...
Then Id connect to the database in case the login fails and save the status bloqued and the time stamp. the next attempt you would check the time.now vs last access...
I good suggestion would be create a function for the database connection so you can call it a couple of time without repeat the code, also dont forget use the try/except fot the db connection.

Error Updating Old Password with with password_hash

I've a problem when updating the old password with the new one password_hash, it always said Old password is wrong.
The table: pegawai
Field: nokom, nama, uol1
Here's my code:
<?php session_start();
require "config.php";
$nokom = $_POST['nokom'];
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
$pswbaru = password_hash($_POST['pswbaru'], PASSWORD_DEFAULT);
$cari = "SELECT * FROM pegawai WHERE nokom ='".$nokom."'";
$result = mysqli_query($conn,$cari);
if (mysqli_num_rows($result) > 0)
{
while ($data = mysqli_fetch_array($result))
{
if(password_verify($pswlama, $data['uol1']))
{
$perintah = "UPDATE pegawai SET uol1 = '$pswbaru' WHERE nokom = '$nokom' ";
if (mysqli_query($conn, $perintah))
{
echo "<script>alert('Success');location.replace('home.php')</script>";
}
else
{
echo "Error updating record: " . mysqli_error($conn);
}
}
else
{
echo "<li>Old password is wrong!</li>";
}
}
}
else
{
echo "Data not found";
}
?>
Any help will be great, thanks.
You are putting a hash in both arguments of password_verify. Read the manual of password_verify and you'll see that the first argument is not supposed to be a hash, but the password itself to compare against the hashed password (argument 2) that is stored in your database.
You are hashing the password before you pass it to password_verify here:
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
...
if(password_verify($pswlama, $data['uol1']))
You should be passing $_POST['pswlama'] directly to password_verify.
change this
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
to this. password_verify will handle the rest.
$pswlama = $_POST['pswlama'];
keep the rest of your code the same.

Check if email and username exist in PHP and mysqli

I'm trying to check if a handle or email exists for the riegistration on my mock Twitter project I'm doing called bleeter, but I'm getting this error:
Notice: Object of class mysqli_result could not be converted to int in first.php on line 20
This is the line where I check if num_rows_handle == 0. How am I supposed to do this?
$query_check_handle = "SELECT * FROM users WHERE handle = " . $handle;
$num_rows_handle = mysqli_query($dbc, $query_check_handle);
if ($num_rows_handle == 0) { // Line 20
//check email
$query_check_email = "SELECT * FROM users WHERE email = " . $email;
$num_rows_email = mysqli_query($dbc, $query_check_email);
if ($num_rows_email == 0) {
$query_register = "INSERT INTO users (first_name, last_name, handle, password, email, ACL)
VALUES ('$fname', '$lname', '$handle', '$pass', '$email', '$ACL')"
or DIE ("error running the query.");
mysqli_query($dbc, $query_register);
echo "<br>";
echo "You have succesfully registered, please login";
} else {
echo "<br>";
echo "Email already in use. Please try again";
}
} else {
echo "<br>";
echo "Handle already in use. Please try again";
}
When the query is SELECT, mysqli_query returns the object of type mysqli_result, which has property num_rows containing the number of rows. Thus
$result = mysqli_query($dbc, $query_check_email);
$num_rows_email = mysqli_num_rows($result);

Error with login processing system

I have created a login system for my webpage, but when I enter in the username and password, it fails to get past the first stage of the process. Anyone have any ideas on what the problem maybe, I have provided the code below.
if(!$_POST['client_username'] || !$_POST['client_password']) {
die('You did not fill in a required field.');
}
if (!get_magic_quotes_gpc()) {
$_POST['client_username'] = addslashes($_POST['client_username']);
}
$qry = "SELECT client_username, client_password FROM client WHERE client_username = '".$_POST['client_username']."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) == 1) {
die('That username does not exist in our database.');
}
}
// check passwords match
$_POST['client_password'] = stripslashes($_POST['client_password']);
$info['client_password'] = stripslashes($info['client_password']);
$_POST['client_password'] = md5($_POST['client_password']);
if ($_POST['client_password'] != $info['client_password']) {
die('Incorrect password, please try again.');
}
// if we get here username and password are correct,
//register session variables and set last login time.
$client_last_access = 'now()';
$qry = "UPDATE client SET client_last_access = '$client_last_access' WHERE client_username = '".$_POST['client_username']."'";
if(!mysql_query($insert,$con)) {
die('Error: ' . mysql_error());
}
else{
$_POST['client_username'] = stripslashes($_POST['client_username']);
$_SESSION['client_username'] = $_POST['client_username'];
$_SESSION['client_password'] = $_POST['client_password'];
echo '<script>alert("Welcome Back");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
When I fill in the username and password, it dies at the first stage and shows the message:
You did not fill in a required field.
You should use || instead of a simple |.
I'm in a good mood.
Here's your code. It should work.
<?php
if( empty( $_POST['client_username'] ) || empty( $_POST['client_password'] ) ) {
die('You did not fill in a required field.');
}
$qry = sprintf( "SELECT client_username, client_password FROM client WHERE client_username = '%s' LIMIT 1", mysql_real_escape_string( $_POST['client_username'] ) );
$result = mysql_query( $qry );
if( $result ) {
if( mysql_num_rows( $result ) == 0 ) {
die('That username does not exist in our database.');
}
}
// where the f**k do you get your info? i added some.
$info = mysql_fetch_assoc( $result );
if( md5( $_POST['client_password'] ) != $info['client_password'] ) {
die('Incorrect password, please try again.');
}
// if we get here username and password are correct,
//register session variables and set last login time.
$qry = sprintf( "UPDATE client SET client_last_access = NOW() WHERE client_username = '%s'", $info['client_username'] );
if( !mysql_query( $qry ) ) {
die('Error: ' . mysql_error() );
} else {
$_SESSION['client_username'] = $info['client_username'];
$_SESSION['client_password'] = $info['client_password'];
echo '<script>alert("Welcome Back");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
Your login code contains serious flaws which lead to security issues. In short: magic_quotes compatibility and SQL injection. I don't cover them. Your problem you highlight in your question is the one | when you meant || in the first stages if clause:
if (!$_POST['client_username'] || !$_POST['client_password'])
^^
See Logical Operators Docs. You've used a Bitwise Operator Docs.

Why am I getting Error: Query was empty?

I am creating a login part to my web page. When a new person registers their details, pressing the register button goes to a register_ok part, showing below:
case 'register_ok':
if (!$_POST['client_username'] || !$_POST['client_password'] ||
!$_POST['client_email']) {
die('You did not fill in a required field.');
}
// check if username exists in database.
if (!get_magic_quotes_gpc()) {
$_POST['client_username'] = addslashes($_POST['client_username']);
}
$qry = "SELECT client_username FROM client WHERE client_username = '".$_POST['client_username']."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
die('Sorry, the username: <strong>'.$_POST['client_username'].'</strong>'
. ' is already taken, please pick another one.');
}
}
// check e-mail format
if (!preg_match("/.*#.*..*/", $_POST['client_email']) ||
preg_match("/(<|>)/", $_POST['client_email'])) {
die('Invalid e-mail address.');
}
// no HTML tags in username, website, location, password
$_POST['client_username'] = strip_tags($_POST['client_username']);
$_POST['client_password'] = strip_tags($_POST['client_password']);
// now we can add them to the database.
// encrypt password
$_POST['client_password'] = md5($_POST['client_password']);
if (!get_magic_quotes_gpc()) {
$_POST['client_password'] = addslashes($_POST['client_password']);
$_POST['client_email'] = addslashes($_POST['client_email']);
}
$insert = "INSERT INTO client (
client_username,
client_password,
client_name,
client_email,
client_last_access)
VALUES (
'".$_POST['client_username']."',
'".$_POST['client_password']."',
'".$_POST['client_name']."',
'".$_POST['client_email']."',
'now()'
)";
if(!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
else{
$id= mysql_insert_id();
session_start();
echo '<script>alert("You May Now Login");</script>';
echo '<meta http-equiv="Refresh" content="0;URL=pv.php">';
}
break;
}
When I register a new person, I get the following error:
Error: Query was empty
Why is this?
In the line if(!mysql_query($sql,$con)) {, do you mean $insert instead of $sql?
Do:
if(!mysql_query($sql,$con)) {
to
if(!mysql_query($insert,$con)) {
your variable name is not correct

Categories