I want to display an error if a username exists, however no error is being thrown.
the function is on the User.php and im trying to display an error from that function.
i referenced this, however it is not relevant to the OOP way.
User.php
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$row['user_name'] == $username;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Index.php
<?php
session_start();
require_once 'User.php';
$guest = new User();
if($guest->is_logged())
{
$guest->redirect('profile');
}
if (isset($_POST['btn_signup']) ){
$username = htmlentities($_POST['txt_username']);
$unpass = htmlentities($_POST['txt_password']);
$password = password_hash($unpass, PASSWORD_BCRYPT, ['cost' => 12] );
$unemail = $_POST['txt_email'];
$email = filter_var($unemail, FILTER_VALIDATE_EMAIL);
$guest = new User();
if($email == ""){
$errors[]= "Enter a Email";
}
if($username == ""){
$errors[]= "Enter a Username please";
}
if($password == ""){
$errors[]= "Enter a Password";
}
if($guest->check_user_exists($username)){
$errors[]= "Username Already Taken";
}
if($guest->signup($email,$password,$username)){
$guest->redirect('profile');
die('didnt redirect');
}
else{
$errors[]= "Invalid Entry";
}
}
$title = "Home";
require_once 'layouts/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php
if(isset($errors))
{
foreach($errors as $error)
{
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered <a href='index.php'>login</a> here
</div>
<?php
}
?>
<h1>Sign Up</h1>
<form action ="" method="POST">
<div class="form-group">
<label for="Email">Email address</label>
<input type="email" class="form-control" aria-describedby="emailHelp" name="txt_email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" aria-describedby="emailHelp" name="txt_username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" aria-describedby="emailHelp" name="txt_password" placeholder="Enter password">
</div>
<button type="submit" name="btn_signup" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
return $stmt->fetchColumn() > 0; // fetchColumn return the number of rows selected
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Your function doesn't actually return or do anything. Return the result of fetch(), if it returns true - a result was found. If it returns false, there was no row matching the username. You don't need to check anything after that, as the fetch() method will only be true if a result was found.
Adjusted for that, your function would look like this
public function check_user_exists($username) {
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username' => $username));
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOExeception $e) {
echo $e->getMessage();
}
}
Also, its not a good idea to output errors directly (on a testing/development environment its fine, but on a live environment you should log it (error_log()) instead.
http://php.net/manual/en/pdostatement.fetch.php
public function ifUserAlreadyExist(string $email):bool{
$sql = "SELECT 1 FROM users WHERE email= :Email";
$statment = $this->conn->prepare($sql);
if (false === $statment) {
return false;
}
$statment->execute([':Email' => $email]);
return (bool)$statment->fetchColumn();
}
//You need to just select 1 object if is already exist and in this case function hint will be so handy, can set the function to boolean and see if it return true or false.
I hope I could help.
Related
This is my custom user registration form WordPress site, actually, this is my first custom development, and here all the data passes the DB my problem is I need to show my error message inside the HTML code. how can I do it? can anyone help me to solve this problem? now my error messages show like this (Array ( [username_empty] => Needed Username [email_valid] => Email has no valid value [texnumber_empty] => Needed Tax Number )) but I need only show error message only Ex: this one ( [username_empty] => Needed Username) I need to show "Needed Username"
Like this.
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
$error = array();
if (strpos($username, ' ') !== FALSE) {
$error['username_space'] = "Username has Space";
}
if (empty($username)) {
$error['username_empty'] = "Needed Username";
}
if (username_exists($username)) {
$error['username_exists'] = "Username already exists";
}
if (!is_email($email)) {
$error['email_valid'] = "Email has no valid value";
}
if (email_exists($email)) {
$error['email_existence'] = "Email already exists";
}
if (empty($taxnumber)) {
$error['texnumber_empty'] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$error['password'] = "Password didn't match";
}
if (count($error) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($error);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($error as $error) {
echo $error . "<br>";
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};
This is my code I will try many times but I can't get the error messages inside the HTML body.
You want to make an AJAX call to register a user then use a callback function to check for success. If a field is invalid you also check it with javascript.
So you would need to refactor your code, seperate it into frontend/backend code and connect it via AJAX.
Write your PHP code as "add_action_hook" and register function
Onclick validate fields and inputs
Call the hook via AJAX (url: "/wp-admin/admin-ajax.php")
Return result
These are just very abstract steps, you'll need to gather some intel for yourself. You could take a look at this: https://awhitepixel.com/blog/wordpress-use-ajax/ and https://docs.wpvip.com/technical-references/security/validating-sanitizing-and-escaping/
I would do something like this
if (is_user_logged_in()) {
// echo '<script>alert("Welcome, registered user!")</script>';
echo '<script type="text/javascript">';
echo 'alert("Welcome, registered user!");';
echo 'window.location.href = "Url";';
echo '</script>';
} else {
// echo 'Welcome, visitor!';
global $wpdb;
if ($_POST) {
$username = $wpdb->escape($_POST['user_login']);
$email = $wpdb->escape($_POST['user_email']);
$taxnumber = $wpdb->escape($_POST['tax_number']);
$password = $wpdb->escape($_POST['user_pass']);
$ConfPassword = $wpdb->escape($_POST['user_confirm_password']);
if (strpos($username, ' ') !== FALSE) {
$errorMsg[] = "Username has Space";
}
if (empty($username)) {
$errorMsg[] = "Needed Username";
}
if (username_exists($username)) {
$errorMsg[] = "Username already exists";
}
if (!is_email($email)) {
$errorMsg[] = "Email has no valid value";
}
if (email_exists($email)) {
$errorMsg[] = "Email already exists";
}
if (empty($taxnumber)) {
$errorMsg[] = "Needed Tax Number";
}
if (strcmp($password, $ConfPassword) !== 0) {
$errorMsg[] = "Password didn't match";
}
if (count($errorMsg) == 0) {
$user_id = wp_create_user($username, $password, $email);
$userinfo = array(
'ID' => $user_id,
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
'role' => 'customer',
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_user_meta($user_id, 'tax_number', $taxnumber);
echo '<script type="text/javascript">';
echo 'alert("User Created Successfully");';
echo 'window.location.href = "url";';
echo '</script>';
exit();
} else {
print_r($errorMsg);
}
}
?>
<section id="wholesale-custom-register-form">
<div class="container wholesale-custom-register-form">
<div class="register-form">
<div class="register-form-title">
<h1>Wholesale Register Form</h1>
</div>
<div class="wholesale-register">
<form class="register-fm" method="POST">
<div class="form-group">
<label>User Name</label>
<input class="form-control" type="text" name="user_login" id="user_login" placeholder="Username" />
<?php foreach ($errorMsg as $error) {
?>
<div>
<strong><?= $error; ?> </strong>
</div>
<?php
} ?>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="email" name="user_email" id="user_email" placeholder="Email" />
</div>
<div class="form-group">
<label>Tax Number</label>
<input class="form-control" type="text" name="tax_number" id="tax_number" placeholder="Tax Number" />
</div>
<div class="form-group">
<label>Enter Password</label>
<input class="form-control" type="password" name="user_pass" id="user_pass" placeholder="Password" />
</div>
<div class="form-group">
<label>Enter Cofirm Password</label>
<input class="form-control" type="password" name="user_confirm_password" id="user_confirm_password" placeholder="Cofirm Password" />
</div>
<div class="form-group">
<button class="custom-register-btn" type="submit" name="btnsubmit">Log In</button>
</div>
</form>
</div>
</div>
</div>
</section>
<?php
};
index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>
I read on stack overflow about flash data only valid till next server request, therefore I made new flashdata for couple of message display..
here below is the my code
This is my controller Controller
public function login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|min_length[5]');
if($this->form_validation->run() == TRUE){
$username= $this->input->post('username');
$password= $this->input->post('password');
$this->load->model('Auth_model');
$user = $this->Auth_model->get_login();
if ($user == 0) {
//echo "<script>alert('wrong username');</script>";
$this->session->set_flashdata("msg","Username does not exists");
redirect("auth/login");
}
else{
print_r($user['username']);
if($username == $user['username'] && $password == $user['password']){
$this->session->set_flashdata("success","You are logged in");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user['username'];
redirect("user/dashboard","refresh");
}
else {
//echo "<script>alert('wrong password');</script>";
$this->session->set_flashdata("msg","Password does not match.");
redirect("auth/login");
}
}
}
$this->load->view('login_v');
}
Model
public function get_login(){
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username' => $username));
$query = $this->db->get();
$user = $query->row();
if ($this->db->affected_rows() != 1) {
return false;
}
else {
$data = array(
'user_id' => $user->user_id,
'username' => $user->username,
'password' => $user->password
);
//print_r($data);
//$this->session->set_userdata($data);
return $data;
}
}
view
<?php if(isset($_SESSION['success'])) {?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?></div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php $this->session->flashdata('msg');?>
<form action="" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" id="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" id="password">
</div>
<div>
<button class="btn btn-primary" name="login">Login</button>
</div>
</form>
I want to display
$this->session->set_flashdata("msg","Username does not exists");
but my if else is just doing redirect, the commented script tag works fine though.
How to make "msg" work?
Thanks in advance.
please add echo statement in the view like
<?php echo $this->session->flashdata('msg');?>
OR
<?=$this->session->flashdata('msg')?>
It should be like this :
Get your flashdata by using its key, Should be like this
<?php if(!empty($this->session->flashdata('msg'))) {?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('msg'); ?>
</div>
<?php } ?>
Or simply do like this:
<div class="alert alert-success"><?php echo $this->session->flashdata('msg'); ?></div>
For more : https://www.codeigniter.com/user_guide/libraries/sessions.html
I have recently learned Object Oriented Programming PHP, and I tried to test my knowledge on that, so I tried to write some queries by myself...
(Example practice: inserting new row, updating a row and deleting a row).
And here is of the templates that I've coded myself in order to Insert New Row into database:
class Register
{
protected $notice = array();
private $_db;
public function __construct()
{
$this->_db = new Connection();
$this->_db = $this->_db->dbConnect();
}
public function CheckUname($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$chk1 = $this->_db->prepare("SELECT user_name FROM admins WHERE user_name = ?");
$chk1->bindParam(1,$username);
$chk1->execute();
if($chk1->rowCount() == 1)
{
$notice['username_exists'] = "Try different username";
return $this->notice;
}else{
$chk2 = $this->_db->prepare("SELECT email_address FROM admins WHERE email_address = ?");
$chk2->bindParam(1,$email);
$chk2->execute();
if($chk2->rowCount() == 1)
{
$notice['email_exists'] = "The email address that you have entered is already exists in database";
return $this->notice;
}else{
$this->NewAdmin($username,$email,$password,$groups,$level);
$notice['success_message'] = "New admin was successfully added";
return $this->notice;
}
}
}
}
public function NewAdmin($username,$email,$password,$groups,$level)
{
if(!empty($username)&&!empty($email)&&!empty($password)&&!empty($groups)&&!empty($level))
{
$reg = $this->_db->prepare("INSERT INTO admins (user_name, email_address, password_hash, group_admin, date_joined, admin_level) VALUES ( ?, ?, ?, ?, NOW(), ?)");
$reg->bindParam(1,$username);
$reg->bindParam(2,$email);
$reg->bindParam(3,$password);
$reg->bindParam(4,$groups);
$reg->bindParam(5,$level);
$reg->execute();
}
}
public function getNotice()
{
return $this->notice;
}
}
And I called this Class on index:
<?php
if (isset($_POST['submit'])){
$username = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['pass'];
$groups = $_POST['groups'];
if($groups == "Administrator"){
$level = 2;
}else if($groups == "ContentCreatorBlog"){
$level = 3;
}else if($groups == "ContentCreatorShop"){
$level = 4;
}else if($groups == "ContentCreatorGallery"){
$level = 5;
}else if($groups == "Secretary"){
$level = 6;
}else if($groups == "SocialMediaManager"){
$level = 7;
}else if($groups == "Analyst"){
$level = 8;
}else{
$level = Null;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$notice['email_validation'] = "The email that you have entered is not a valid one";
}else{
$registration = new Register();
$notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);
}
}
?>
<div class="content-wrapper">
<section class="content-header">
<h1>
Add New Admin
<small>You can add new admin here</small>
</h1>
<ol class="breadcrumb">
<li class="active">addnewadmin.php</li>
</ol>
</section>
<section class="content">
<div class="row">
<div class="col-md-12">
<div class="box box-primary" id="myModal1">
<div class="box-header with-border">
<h3 class="box-title">Required Information</h3>
</div>
<?php
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
?>
<form role="form" method="POST" action="" data-tour-index="1" data-tour-title="Card Type" data-tour-description="A card will usually be one of multiple similar type items on a page.">
<div class="box-body">
<div class="form-group">
<label>User name</label>
<input type="text" class="form-control" placeholder="Enter username" name="uname" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Temporary password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Enter password" name="pass" required>
</div>
<div class="form-group">
<label>Group admin</label>
<select class="form-control" name="groups">
<option value="Administrator">Administrator</option>
<option value="ContentCreatorBlog">Blog Content Creator</option>
<option value="ContentCreatorShop">Shop Content Creator</option>
<option value="ContentCreatorGallery">Gallery Content Creator</option>
<option value="Secretary">Secretary</option>
<option value="SocialMediaManager">Social Media Manager</option>
<option value="Analyst">Analyst</option>
</select>
</div>
</div>
<div class="box-footer">
Visit admin new documentation to know more about this page.
</div>
<div class="box-footer">
<button name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
So shortly what it does is showing the form and take some information and assign to parameters and then call the Class:
$registration = new Register();
$notice[] = $registration->CheckUname($username,$email,$password,$groups,$level);
So if the form faced any error such as:
already registerd username error
already exists email address error
It should simply take back an error message and show it to users by these code on the index page:
if(isset($notice['email_validation'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_validation'].".
</div>
";
}
if(isset($notice['username_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['username_exists'].".
</div>
";
}
if(isset($notice['email_exists'])) {
echo "
<div class='alert alert-danger'>
<strong>Hey!</strong> ".$notice['email_exists'].".
</div>
";
}
if(isset($notice['success_message'])) {
echo "
<div class='alert alert-success'>
<strong>Hey!</strong> ".$notice['success_message'].".
</div>
";
}
Question:
The problem with this code is that the error messages does not pop up when a user enters information despite of the rules. However it still adds new row to table correctly.
So now the question is "Why the errors does not show up on page when users enters wrong information? Which part I made a mistake"
There's an diffrence between $notice and $this->notice. $notice is a local var and $this->notice is a class var. In your case, you only create a local var, assign a value, but return the still empty class var.
To fix this, simply replace it with $this->notice[..] = ....
But there are also other logical issues. Why does CheckUname creates a user? It would be the task of NewAdmin to call CheckUname. Also you could merge the two database queries into one, asking, if there's a entry with the username or the password. There's more to fix/change, but that would be part of Code Review
Your $notice variable will always be "not set" below. All the variables will be reset after post processing. However, you can redirect to the url that has the $notice variable. For instance, after all the processing you can:
redirect_to('index.php?notice=1');
where redirect_to is a function that takes a url.
function redirect_to($path){
die("<meta http-equiv='refresh' content=0;URL='".$path."' />");
}
And then in your index.php, you can check the notice variable if it is set. There are different ways on how to do this though.
EDIT:
function redirect_to($path){
header("Location: " . $path);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i was trying to make from scratch a PDO, OOP user/register system in PHP and i got stucked in the point where I don't understand why I it's trowing me the handle request error.
This is my index.php file with login and register:
<?php
require_once('inc/config.php');
if($user->is_loggedIn()!="") {
$user->redirect('account.php');
}
// login
if(isset($_POST['login-submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username, $password)) {
$user->redirect('account.php');
}
else {
$error[] = "Username or Password are not correct!";
}
}
//register
if(isset($_POST['register-submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if($username == "") {
$error[] = "You need to specify a username!";
}
else if($password == "") {
$error[] = "Please add a password!";
}
else if(strlen($password) < 6) {
$error[] = "Password must have at least 6 characters";
}
else {
try {
$stmt = $db_connection->prepare("SELECT username FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
// execute(array(':user_name'=>$username));
$row->$stmt->fetch(PDO::FETCH_ASSOC);
if($row['username'] == $username) {
$error[] = "Sorry, this username is already taken!";
}
else {
if($user->register($username, $password)) {
$user->redirect('index.php?success');
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login/Register</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
Login
</div>
<div class="col-xs-6">
Register
</div>
</div>
<hr>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<?php
if(isset($error)) {
foreach($error as $error) {
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
// end for each
}
// end of if statement
} else if(isset($_GET['success'])) { ?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered! You can now log in!
</div>
<?php } ?>
<form id="login-form" action="#" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group text-center">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
</div>
</div>
</div>
</div>
</form>
<form id="register-form" action="#" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/tabs.js"></script>
</body>
</html>
This is my config.php:
<?php
session_start();
//set timezone
date_default_timezone_set('Europe/Copenhagen');
//database credentials
define('DBHOST','localhost');
define('DBUSER','admin');
define('DBPASS','Ddy6MUXhtUz3mNpE');
define('DBNAME','notes_app');
//application address
define("BASE_URL","/");
define("ROOT_PATH",$_SERVER['DOCUMENT_ROOT'] . "/");
try {
$db_connection = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e) {
echo "Connection failed " . $e->getMessage();
die();
}
include_once('models/user.php');
$user = new User($db_connection);
And this is my user model:
<?php
class User {
private $db;
function __construct($db_connection) {
$this->db = $db_connection;
}
public function register($username, $password) {
try {
$crypted_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users(username, password) VALUES(:user_name, :user_pass)");
$stmt->execute(array(":user_name"=>$username, ":user_pass"=>$crypted_password));
return $stmt;
}
catch(Exception $e) {
echo $e->getMessage();
}
}
public function login($username, $password) {
try {
$stmt = $this->db->prepare("SELECT * FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($username, $userRow['password'])) {
$_SESSION['user_session'] = $userRow['id'];
return true;
}
else {
return false;
}
}
}
catch(Exception $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;
}
}
I was trying for several hours to find the problem but unfortunately I couldn't find it, I cannot neither print the var_dump because my browser is receiving the internal error 500.
The problem is because of the following lines:
In your login() method of User class,
if(password_verify($username, $userRow['password'])) { ...
And on index.php page, during the processing of registration form,
$row->$stmt->fetch(PDO::FETCH_ASSOC);
So your login() method should be like this:
public function login($username, $password) {
try {
$stmt = $this->db->prepare("SELECT * FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($password, $userRow['password'])) {
$_SESSION['user_session'] = $userRow['id'];
return true;
}else{
return false;
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
And change this line
$row->$stmt->fetch(PDO::FETCH_ASSOC);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);