I'm making a sort of instagram and therefor I need a register page. I want to check of the password is equal or longer than 8 characters and if password and passwordconfirmation are the samen.
I've tried making a new class Security or a try - catch.
register.php
if ( !empty($_POST)) {
$user = new User();
$user->setFullname($_POST['fullname']);
$user->setUsername($_POST['username']);
$user->setEmail($_POST['email']);
$user->setPassword($_POST['password']);
$user->setPasswordConfirmation($_POST['password_confirmation']);
if( $user->passwordsAreSecure()) {
if($user->register()) {
session_start();
$_SESSION['email'] = $user->getEmail();
header('location: index.php');
} else {
$error = true;
}
} else {
$error2 = true;
}
}
My user class
public function passwordIsStrongEnough(){
if( strlen( $this->password ) <= 8 ){
return false;
}
else {
return true;
}
}
public function passwordsAreEqual(){
if( $this->password == $this->passwordConfirmation ){
return true;
}
else {
return false;
}
}
public function passwordsAreSecure(){
if( $this->passwordIsStrongEnough()
&& $this->passwordsAreEqual() ){
return true;
}
else {
return false;
}
}
function register
public function register() {
$password = Security::hash($this->password);
try {
$conn = Db::getInstance();
$statement = $conn->prepare('INSERT INTO users (fullname, username, email, password) values (:fullname, :username, :email, :password)');
$statement->bindParam(':fullname', $this->fullname);
$statement->bindParam(':username', $this->username);
$statement->bindParam(':email', $this->email);
$statement->bindParam(':password', $password);
$result = $statement->execute();
return($result);
} catch ( Throwable $t ) {
return false;
}
}
I want to get to the if( $user->passwordsAreSecure()) { so there is a session but now the form fields go empty and nothing happens.
I'm not sur to understand where is you problem. You haven't ask any question... But you can do all your code just like this :
if (!empty($_POST)) {
$user = new User();
$user->setFullname($_POST['fullname']);
$user->setUsername($_POST['username']);
$user->setEmail($_POST['email']);
$user->setPassword($_POST['password']);
$user->setPasswordConfirmation($_POST['password_confirmation']);
if ($_POST['password'] == $_POST['password_confirmation']
&& strlen($_POST['password']) > 8) {
if ($user->register()) {
session_start();
$_SESSION['email'] = $user->getEmail();
header('location: index.php');
} else {
$error = true;
}
} else {
$error2 = true;
}
}
Related
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 !.
SIGNUP.PHP/HTML
<?php
require_once("connections/db.php");
$error = array();
if($user->is_loggedin())
{
$user->redirect('index.php');
}
if(isset($_POST['signup-btn']))
{
$username = $_POST['signup-username'];
$password = $_POST['signup-password'];
$email = $_POST['signup-email'];
if($user='')
{
$error[] = "Please enter a username";
}
else if($pass='')
{
$error[] = "Please enter a password";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$error[] = "Please enter a valid email address";
}
else
{
try
{
if($user->register($username, $password, $email))
{
echo "registered";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>
class.user.php
<?php
class USER{
private $db;
function __construct($db_con)
{
$this->db = $db_con;
}
public function register($username,$password,$email)
{
try
{
$protected_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users(username,password,email)
VALUES(:username, :password, :email)");
$stmt->bindparam(":username", $username);
$stmt->bindparam(":password", $protected_password);
$stmt->bindparam(":email", $email);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if (isset($_SESSION['user_session']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
}
?>
db.php
<?php
session_start();
$connection = parse_ini_file('config.ini');
try{
$db_con = new PDO("mysql:host={$connection['host']}; dbname={$connection['dbname']}", $connection['username'], $connection['password']);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
include_once 'class.user.php';
$user = new USER($db_con);
?>
I keep receiving the error Fatal error: Call to a member function register() on string in C:\xampp\we\signup.php on line 32
I'm completely new to PDO's. and I can't see why this is not working.
I tried changing the code up as much as I could, but this error doesn't change. I'm sure it's a simple stupid problem i'm overlooking as well.
We start out setting $username from your form
$username = $_POST['signup-username'];
Then I assume an equality check was meant to happen on this variable ($username == ''?) but instead $user is set to an empty string.
if($user='')
{
$error[] = "Please enter a username";
}
Afterwards, $user->register() is called, and $user is still a string instead of an instance of your class USER.
Be careful that you dont put in variable assignments where you meant to put in equality checks elsewhere! I do it all the time.
if($user='')
{
$error[] = "Please enter a username";
}
else if($pass='') // should this be $password == ''?
{
$error[] = "Please enter a password";
}
I am trying to login with GET method in PHP.
I tried:
login.php
<?php
session_start();
require_once 'class.user.php';
$user_login = new USER();
if($user_login->is_logged_in()!="")
{
$user_login->redirect($web.$_SESSION['user_name']);
}
if(isset($_GET['user']) && isset($_GET['password']))
{
$uname = trim($_GET['user']);
$upass = trim($_GET['password']);
if($user_login->login($uname,$upass))
{
$user_login->redirect($uname);
}
}
?>
class.user.php
public function login($uname,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM tbl_users WHERE userName=:username");
$stmt->execute(array(":username"=>$uname));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['userAccess']=="Y")
{
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
$_SESSION['loggedin_time'] = time();
$_SESSION['user_name'] = $userRow['userName'];
return true;
}
else
{
header("Location: signin.php?error");
exit;
}
}
else
{
header("Location: default.php");
exit;
}
}
else
{
header("Location: inactive.php");
exit;
}
}
else
{
header("Location: signin.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
I am always getting error showing that: wrong details
I cross checked the user name & password with MySQL. They are correct!
This is because you are encrypting your encrypted password, which results in wrong details
Change if($userRow['userPass']==md5($upass)) to if($userRow['userPass']==($upass))
Hope this will resolve your error.
I am trying to make my own custom CMS, I can register users and can login aswel, Now I am trying to make a function for user roles,
File: class.user.php
function getUserrole() {
$username = htmlentities($_SESSION['user_session']);
$stmt = $this->db->prepare('SELECT * FROM users WHERE user_name = :username');
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userrole = $row['user_role'];
if($userrole == 3) {
return $userrole = 3;
}
if($userrole == 2) {
return $userrole = 2;
}
if($userrole == 1) {
return $userrole = 1;
}
if($userrole == 0) {
return $userrole = 0;
}
}
File: Home.php
<?php
$userrole = getUserrole();
if($userrole == 1) {
echo "Hi Admin";
}
else {
echo "You are not a admin";
}
?>
When I try to do this, the error shows up:
Fatal error: Call to undefined function getUserrole() in /Applications/MAMP/htdocs/test/home.php on line 24
I can see something wrong and I was hoping you guys could help me out here:)
Entire class.user.php :
<?php
class USER
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function register($uname,$umail,$upass)
{
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass)
VALUES(:uname, :umail, :upass)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function login($uname,$umail,$upass)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname OR user_email=:umail LIMIT 1");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if(password_verify($upass, $userRow['user_pass']))
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
unset($_SESSION['user_session']);
return true;
}
function getUserrole() {
$username = htmlentities($_SESSION['user_session']);
$stmt = $this->db->prepare('SELECT * FROM users WHERE user_name = :username');
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$userrole = $row['user_role'];
if($userrole == 3) {
return $userrole = 3;
}
if($userrole == 2) {
return $userrole = 2;
}
if($userrole == 1) {
return $userrole = 1;
}
if($userrole == 0) {
return $userrole = 0;
}
}
}
?>
Require the class within your home.php, init it and than call the function
<?php
require_once 'class.user.php';
$userClass = new USER(<yourdbcon>);
$userrole = $userClass->getUserrole();
if($userrole == 1) {
echo "Hi Admin";
}
else {
echo "You are not a admin";
}
?>
(Sorry if this is a nooby question - I am new to PhP)
So I've got the registration page set up nicely, and with it adding to the MySQL database, however, when i go to login with the correct details I get the error:
PHP Fatal error: Call to undefined method User::authenticate() in
here's my ClassUser code
`
function __construct() {
if(session_id() == "") {
session_start();
}
if (isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] == true) {
$this->_initUser();
}
}//end__construct
public function autheniticate($user,$pass) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$safeUser = $mysqli->real_escape_string($user);
$incomingPassword = $mysqli->real_escape_string($pass);
$query = "SELECT * from Customer WHERE email = '{$safeUser}'";
if (!$result = $mysqli->query($query)) {
error_log("Cannot retrieve account for {$user}");
return false;
}
//Will be obly one row, so no while() loop needed
$row = $result->fetch_assoc();
$dbPassword = $row['password'];
if (crypt($incomingPassword, $dbPassword) != $dbPassword ) {
error_log("Passwords for {user} don't match");
return false;
}
$this->id = $row['id'];
$this->username = $row['username'];
$this->isLoggedIn = true;
$this->_setSesstion();
return true;
}//end function authenticate
private function _setSession() {
if(session_id() == '') {
session_start();
}
$_SESSION['id'] = $this->id;
$_SESSION['username'] = $this->username;
$_SESSION['isLoggedIn'] = $this->isLoggedIn;
}//end function setSession
private function _initUser() {
if(session_id() == '') {
session_start();
}
$this->id = $_SESSION['id'];
$this->username = $_SESSION['username'];
$this->isLoggedIn = $_SESSION['isLoggedIn'];
}//end function initUser
}//end classUser
?>`
and here's my login process code;
`
require_once('functions.inc');
//prevent access if they haven't submitted the form
if (!isset($_POST['submit'])) {
die(header("Location: login.php"));
}
$_SESSION['formAttempt'] = true;
if(isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("username","password");
//Check required fields
foreach ($required as $requiredField) {
if (!isset($_POST[$requiredField]) || $_POST[$requiredField] == "") {
$_SESSION['error'][] = $requiredField . " is required.";
}
}
if (count($_SESSION['error']) > 0) {
die(header("Location: login.php"));
} else {
$user = new User;
if($user->authenticate($_POST['email'],$_POST['password'])) {
unset($_SESSION['formAttempt']);
die(header("Location: authenticated.php"));
} else {
$_SESSION['error'][] = "There was a problem with your username and password.";
die(header("Location: login.php"));
}
}
?>
`
`
//Prevent access if they haven't submitted the form
if (!isset($_POST['submit'])) {
die(header("Location: register.php"));
}
$_SESSION['formAttempt'] = true;
if (isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("username", "password1", "password2");
//Check Required Fields
foreach ($required as $requiredField) {
if(!isset($_POST[$requiredField]) || $_POST [$requiredField] == "") {
$_SESSION['error'][] = $requiredField . "is required.";
}
}
if(!preg_match('/^[\w.]+$/',$_POST['username'])) {
$_SESSION['error'][] = "Username must only contain numbers and letters.";
}
if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
$_SESSION['error'][] = "Invalid email address";
}
if($_POST['password1'] != $_POST['password2']) {
$_SESSION['error'][] = "Passwords do not match";
}
//Final disposition
if (count($_SESSION['error']) > 0) {
die(header("Location: register.php"));
} else {
if(registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: register-success.php"));
} else {
error_log("Problem registering user: {$_POST['email']}");
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
function registerUser ($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if($mysqli->connect_errno) {
error_log("Cannot connect to mySQL: " . $mysqli->connect_error);
return false;
}
$email = $mysqli->real_escape_string($_POST['email']);
//Check for an existing user
$findUser = "SELECT id from Customer where email = '{$email}'";
$findResult = $mysqli->query($findUser);
$findRow = $findResult->fetch_assoc();
if(isset($findRow['id']) && $findRow['id'] != "") {
$_SESSION['error'][] = "A user with that email address already exists";
return false;
}
$username = $mysqli->real_escape_string($_POST['username']);
$cryptedPassword = crypt($_POST['password1']);
$password = $mysqli->real_escape_string($cryptedPassword);
$query = "INSERT INTO Customer (email,create_date,password,username) " .
"VALUES('{$email}',NOW(), '{$password}', '{$username}')";
if($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("Inserted ($email) as id ($id)");
return true;
} else {
error_log("Problem inserting {$query}");
return false;
}
}
?>`
any help would be greatly appreciated! Thank you
Your defined function name is:
// You are misspelling "authenticate"
autheniticate($user,$pass)
but you are calling:
authenticate()