Parse error: syntax error, unexpected '?' - php

I have been trying to follow a guide for making a PHP server app and I am getting a few syntax errors.
Error message:
Parse error: syntax error, unexpected '?' in
D:\inetpub\wwwroot\cmpswoo1\CMPPROJ_Web\ServerApp\api2\db_functions2.php on line 134
So I know were the error is, I just don't know how to fix it
<?php
class db_functions2 {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'db_connect2.php';
// connecting to database
$this->db = new db_connect2();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Random string which is sent by mail to reset password
*/
public function random_string()
{
$character_set_array = array();
$character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
$character_set_array[] = array('count' => 1, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}
public function forgotPassword($forgotpassword, $newpassword, $salt){
$result = mysql_query("UPDATE `Users` SET `encryptedPassword` = '$newpassword',`salt` = '$salt'
WHERE `email` = '$forgotpassword'");
if ($result) {
return true;
}
else
{
return false;
}
}
/**
* Adding new user to mysql database
* returns user details
*/
public function storeUser($FirstName, $LastName, $DOB, $email, $Username, $Password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($Password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO Users(unique_id, FirstName, LastName, email, DOB, Username, encryptedPassword, salt, created_at) VALUES('$uuid', '$FirstName', '$LastName', '$email', '$DOB', '$Username', '$encryptedPassword', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM Users WHERE uid = $id");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
/**
* Verifies user by username and password
*/
public function getUserByUsernameAndPassword($Username, $Password) {
$result = mysql_query("SELECT * FROM Users WHERE usernameE = '$Username'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encryptedPassword'];
$hash = $this->checkhashSSHA($salt, $Password);
// check for password equality
if ($encryptedPassword == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
/**
* Checks whether the username is valid or fake
*/
public function validUsername($Username)
{
$isValid = true;
$atIndex = strrpos($Username, "#");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($Username, $atIndex+1);
$local = substr($Username, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\.\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\-\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\.\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if
(!preg_match('/^(\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/',str_replace("\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\"|[^"])+"$/',
str_replace("\\","",$local)))
{
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") ||checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
/**
* Check user is existed or not
*/
public function isUserExisted($Username) {
$result = mysql_query("SELECT Username from Users WHERE Username = '$Username'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
/**
* Encrypting password
* returns salt and encrypted password
*/
public function hashSSHA($Password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($Password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* returns hash string
*/
public function checkhashSSHA($salt, $Password) {
$hash = base64_encode(sha1($Password . $salt, true) . $salt);
return $hash;
}
}
?>

Here single quote is causing problem:
So, change
(!preg_match('/^(\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/',str_replace("\\","",$local)))
To:
(!preg_match('/^(\\.|[A-Za-z0-9!#%&`_=\/$\'*+?^{}|~.-])+$/',str_replace("\\","",$local)))

The regular expression string is opened with ', but also contains a '. Escape it with \. The error should be gone.
(!preg_match('/^(\\.|[A-Za-z0-9!#%&`_=\/$'*+?^{}|~.-])+$/',str_replace("\\","",$local)))
Should be
(!preg_match('/^(\\.|[A-Za-z0-9!#%&`_=\/$\'*+?^{}|~.-])+$/',str_replace("\\","",$local)))

Related

Always able to login even when password is incorrect

I can always log in even when the password is incorrect.
I tried changing if (password_verify($this->concatPasswordWithSalt($password, $salt), $passwordHash)) to if ('aaa' === 'bbb') but it also returns true...
Here is some code:
function getUser($email, $password)
{
$query = "SELECT name, password, salt FROM user WHERE email = ?";
if ($stmt = $this->con->prepare($query)) {
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($name, $passwordHash, $salt);
if ($stmt->fetch()) {
if (password_verify($this->concatPasswordWithSalt($password, $salt), $passwordHash)) {
return true;
} else {
return false;
}
} else {
return false;
}
$stmt->close();
}
}
function concatPasswordWithSalt($password, $salt)
{
global $random_salt_length;
if ($random_salt_length % 2 == 0) {
$mid = $random_salt_length / 2;
} else {
$mid = ($random_salt_length - 1) / 2;
}
return
substr($salt, 0, $mid - 1) . $password . substr($salt, $mid, $random_salt_length - 1);
}
I insert password hash to database with this code:
$passwordHash = password_hash($db->concatPasswordWithSalt($password, $salt), PASSWORD_DEFAULT);
function getSalt()
{
global $random_salt_length;
return bin2hex(openssl_random_pseudo_bytes($random_salt_length));
}
Edit:
Tried to add return false at the end of getUser but it's still not working. So maybe something wrong in login.php:
if (isset($input['email']) && isset($input['password'])) {
$email = $input['email'];
$password = $input['password'];
if (!$db->getUser($email, $password)) {
$response['status'] = 0;
$response['message'] = "Login successful";
} else {
$response['status'] = 1;
$response['message'] = "Invalid email or password";
}
} else {
$response['status'] = 2;
$response['message'] = "Missing mandatory parameters";
}
Your problem:
if (!$db->getUser($email, $password)) {
$response['status'] = 0;
$response['message'] = "Login successful";
}
If the getUser function returns FALSE, say the log in is successful. You have prefixed the function with a !.

Auto-Login After Registration

I want the user to login automatically after registration, been trying this for hours but nothing has worked so far.
The code on index.php that creates the session:
<?php
session_start();
require("inc/user.functions.php");
$sessionkey = "";
if(isset($_SESSION['sessionkey']))
$sessionkey = $_SESSION['sessionkey'];
$account = new Account($sessionkey);
user.funtions.php: (login, registration etc.)
<?php
require("config.php");
require("global.functions.php");
class Account {
public $LoggedIn = false;
public $Username;
public $level;
public $uid;
public $Avatar;
public $admin;
public $Email;
public $Bio;
public function __construct($sessionkey) {
if($sessionkey != "" && $this->session_check($sessionkey) == true) {
$this->LoggedIn = true;
}
}
private function session_check($sessionkey) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE sessionkey = '$sessionkey'");
$check = $query->num_rows;
if($check > 0) {
while($row = $query->fetch_assoc()) {
$this->uid = $row['uid'];
$this->Username = $row['username'];
$this->level = $row['level'];
$this->Avatar = $row['avatar'];
$this->admin = $row['admin_access'];
$this->Email = $row['email'];
$this->Bio = $row['bio'];
}
return true;
}
return false;
}
}
function login_account($username, $password) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE username = '$username' OR email = '$username'");
$check = $query->num_rows;
if($check > 0) {
while($row = $query->fetch_assoc()) {
$uid = $row['uid'];
$hash = $row['password'];
}
if(verifyPassword($password, $hash) == true) {
UpdateSession($uid);
return true;
} else
return false;
} else
return false;
}
function register_account($firstname, $lastname, $gender, $email, $username, $password) {
global $mysql;
//If email is not in correct format e.g example#example.com
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return "Vääränlainen sähköpostiosoite!";
}
//If email exists in the database
if(email_exists($email) == true) {
return "Sähköposti on jo rekisteröity!";
}
//If username exists in the database
if(username_exists($username) == true) {
return "Käyttäjänimi on jo rekisteröity!";
}
$date = date("Y-m-d H:m:s");
//Create a row into table_users
$mysql->query("INSERT INTO table_users (username, password, email, fullname, gender, level, avatar, admin_access, views, date_registered) VALUES ('$username', '".hashPassword($password)."', '$email', '$firstname $lastname', '$gender', 0, 'default.png', 0, 0, '$date') ");
return "Käyttäjätilisi on nyt rekisteröity!";
}
function email_exists($email) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE email = '$email'");
$check = $query->num_rows;
if($check > 0)
return true;
return false;
}
function username_exists($username) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE username = '$username'");
$check = $query->num_rows;
if($check > 0)
return true;
return false;
}
function hashPassword($password) {
return password_hash($password, PASSWORD_BCRYPT, [ 'cost' => 15 ]);
}
function verifyPassword($password, $hash) {
if (password_verify($password, $hash))
return true;
else
return false;
}
function UpdateSession($uid) {
global $mysql;
$sessionkey = base64_encode(randomString(35));
$_SESSION['sessionkey'] = $sessionkey;
$query = $mysql->query("UPDATE table_users SET sessionkey = '$sessionkey' WHERE uid = '$uid'");
}
function sessionkey_check($sessionkey) {
global $mysql;
$query = $mysql->query("SELECT * FROM table_users WHERE sessionkey = '$sessionkey'");
if($query->num_rows > 0)
return true;
return false;
}
?>
Use the $inseted_id=$mysqli->insert_id to get inserted id and all other information you have before. Now create the user SESSION and header location change

User logs in and is redirected to a page specific to them

Hey im creating a site with users that need to log in. For some reason after the user logs in with a successful combination of email and password, they are redirected to a blank index.php instead of the user_page.php that I have created. I know there are other questions similar to this, I have looked through them but was unable to implement their corrections into my own code.
$errors = array();
$message = "";
$email = "";
$password = "";
if(isset($_POST["submit"])) { //THIS CHECKS LOG IN INFORMATION
//form was submitted
//$email = trim($_POST["email"]);
//$password = trim($_POST["password"]);
//header('Location: user_page.php?id=' . $_SESSION['user_id']);
//Validations
$required_fields = array("email", "password");
validate_presences($required_fields);
foreach ($required_fields as $field){
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = ucfirst($field) . " can't be blank"?><br/><?php ;
}
}
if (empty ($errors)) {
//try to login in
$email = trim($_POST["email"]); //set the variables for use in the function so they can be used as a value in the form, if its been submitted prev it echos back
$password = trim($_POST["password"]);
$found_email = attempt_login($email, $password); //function find user or return null or false
if ($found_email) {
// Success
// Mark user as logged in
$_SESSION["email_id"] = $found_email["id"]; //better than using a cookie which is visible in browser
$_SESSION["email"] = $found_email["email"]; //always know what the user name can use it browser or return the value back
redirect_to("user_page.php");
} else {
// Failure
$_SESSION["message"] = "Email/password not found.";//do not alert as to which field was incorrect
}
}
} else {
/*$email = "";
$password = "";
$message = "";*/
} //if isset end
I have a separate page with validations and functions that come from my learning source. if any other information is needed let me know. Thank You!
functions
<?php
function redirect_to($new_location)
{
header("Location: " . $new_location);
exit;
}
function mysql_prep($string)
{
global $connection;
$escaped_string = mysqli_real_escape_string($connection, $string);
return $escaped_string;
}
function password_encrypt($password)
{
$hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of 10
$salt_length = 22; // Blowfish salts should be 22-characters or more
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
function generate_salt($length)
{
// Not 100% unique, not 100% random, but good enough for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid characters for a salt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', '.', $base64_string);
// Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
function password_check($password, $existing_hash)
{
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
function find_all_users()
{
global $connection;
$query = "SELECT * ";
$query .= "From users ";
$query .= "ORDER BY position ASC";
$result = mysql_query($connection, $query);
confirm_query($user_set);
return $user_set;
}
function find_user_by_email($email)
{
global $connection;
$safe_email = mysqli_real_escape_string($connection, $email);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE email = '{$safe_email}' ";
$query .= "LIMIT 1";
$email_set = mysqli_query($connection, $query);
confirm_query($email_set);
if ($email = mysqli_fetch_assoc($email_set)) {
return $email;
} else {
return null;
}
}
function find_email_by_id($email_id)
{
global $connection;
$safe_email_id = mysqli_real_escape_string($connection, $email_id);
$query = "SELECT * ";
$query .= "FROM email ";
$query .= "WHERE id = {$safe_email_id} ";
$query .= "LIMIT 1";
$email_set = mysqli_query($connection, $query);
confirm_query($email_set);
if ($email = mysqli_fetch_assoc($email_set)) {
return $email;
} else {
return null;
}
}
function attempt_login($email, $password)
{
$email = find_user_by_email($email);
if ($email) {
// found user, now check password
if (password_check($password, $email["hashed_password"])) {
// password matches
return $email;
} else {
// password does not match
return false;
}
} else {
// user not found
return false;
}
}
function logged_in()
{
return isset($_SESSION['email_id']);
}
// function confirm_logged_in()
// {
// if (!logged_in()) {
// redirect_to("index.php");
// }
// }
?>

PHP Username and Password Check Failing

When I register as a new user, and then try to login as that user, the username and/or password are not recognized. I've used this login system successfully in another application, but when I plugged it into a new application it started having this problem. I've checked everything and can't seem to find the issue. Any thoughts are greatly appreciated.
Here's the code:
<?php
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE username = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
function password_encrypt($password) {
$hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of 10
$salt_length = 22;
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
function generate_salt($length) {
// Not 100% unique, not 100% random, but good enough for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid characters for a salt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', '.', $base64_string);
// Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
function password_check($password, $existing_hash) {
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
function attempt_login($username, $password) {
$admin = find_admin_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
// validations
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {
// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login($username, $password);
if ($found_admin) {
// Success
// Mark user as logged in
$_SESSION["admin_id"] = $found_admin["id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("MyAccount.php");
} else {
// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>

Get error when trying to send new password to e-mail by php

I'm a beginner of php and now getting stuck on sending a new password to user e-mail if user requested in android.
ForgetPassword.php
<?php
require_once('DB_Functions.php');
$db = new DB_Functions();
$forgotpassword = $_POST['forgotpassword'];
$randomcode = $db->random_string();
if(isset($_POST['forgotpassword'])){
$hash = $db->hashSSHA($randomcode);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"];
$subject = "Password Recovery";
$message = "Hello User,nnYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.nnRegards,nLearn2Crack Team.";
$from = "contact#learn2crack.com";
$headers = "From:" . $from;
if ($db->isUserExisted($forgotpassword)) {
$user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
if ($user) {
$response["success"] = 1;
mail($forgotpassword,$subject,$message,$headers);
echo json_encode($response);
}
else {
$response["error"] = 1;
echo json_encode($response);
}
}
// user is already existed - error response
}
else {
$response["error"] = 2;
$response["error_msg"] = "User not exist";
echo json_encode($response);
}
?>
DB_Functions.php
<?php
require_once('dbConnect.php');
class DB_Functions {
private $db;
/**
* Random string which is sent by mail to reset password
*/
public function random_string()
{
$character_set_array = array();
$character_set_array[] = array('count' => 7, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
$character_set_array[] = array('count' => 1, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}
public function isUserExisted($email) {
$result = mysqli_query($this->db,"SELECT email from users WHERE email = '$email'");
if($result)
{
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
}
}else {
// user not existed
return false;
}
}
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
public function forgotPassword($forgotpassword, $newpassword, $salt){
$result = mysqli_query("UPDATE `users` SET 'password` = '$newpassword'
WHERE `email` = '$forgotpassword'");
if ($result) {
return true;
}
else
{
return false;
}
}
}
?>
dbConnect.php
<?php
define('HOST','127.0.0.1:3307');
define('USER','root');
define('PASS','');
define('DB','androiddb');
//Connecting to Database
$con= mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
This is what I have tried so far, unfortunately it gives me a bunch of error ! Any help would be appreciated .
I get tutorial from here.
Error(latest)
Notice: Undefined index: forgotpassword in
C:\xampp\htdocs\Android\CRUD\forgetPassword.php on line 4
{"error":2,"error_msg":"User not exist"}
Notice: Undefined index: forgotpassword
You have to make sure the index is the same from android & PHP.
Wrap your code around the following check:
if(isset($_POST['forgotpassword'])){//code here}else{//undefined}
Warning: mysqli_query() expects at least 2 parameters, 1 given
As the error says, a param is missing, which is the connection:
$result = mysqli_query($con,"SELECT email from users WHERE email = '$email'");
(Add the connection as a 2nd parameter of your db function)
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result,
null given
this is because the query failed.to avoid this error, add more checks:
if($result){
$no_of_rows = mysqli_num_rows($result);
}else{
//failed
}

Categories