I am building an OOP/PDO login system for my website but, I don't know how I can correctly display error messages within my login class when the user login attempt fails. Also, I would like to know if my OOP approach is right. This is my first project working with OOP and PDO. If you have any suggestions for my code I would like to hear them.
login.class.php
<?php
class Login {
private $dbConnection;
private $studentNumber;
private $studentClass;
private $errorMessage = false;
public function __construct($dbConnection) {
$this->dbConnection = $dbConnection->dbConnection;
}
public function showErrorMessage() {
return $this->errorMessage;
}
public function studentLogin($studentNumber, $studentClass) {
$this->studentNumber = $studentNumber;
$this->studentClass = $studentClass;
$selectStudent = $this->dbConnection->prepare("SELECT * FROM tbl_students WHERE studentNumber = :studentNumber AND studentClass = :studentClass LIMIT 1");
$selectStudent->bindParam(':studentNumber', $this->studentNumber);
$selectStudent->bindParam(':studentClass', $this->studentClass);
$selectStudent->execute();
$selectStudentCheck = $selectStudent->fetch(PDO::FETCH_ASSOC);
if(!empty($selectStudentCheck)) {
return true;
}
else {
$this->errorMessage = "Studentnumber or class is not correct";
}
}
}
?>
dbconnection.class.php
<?php
class DatabaseConnection {
private $DatabaseHost = "localhost";
private $DatabaseName = "plansysteem_keuzetrainingen";
private $userName = "root";
private $passWord = "root";
public $dbConnection;
public function __construct() {
$this->databaseConnect();
}
public function databaseConnect() {
try{
$this->dbConnection = new PDO("mysql:host=$this->DatabaseHost;dbname=$this->DatabaseName", $this->userName, $this->passWord);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
print("Sorry er kan geen verbinding worden gemaakt met de database");
file_put_contents("../errors/database.connection.errors.txt", $e->getMessage().PHP_EOL,FILE_APPEND);
die();
}
}
}
?>
login form
<?php
session_start();
include ("../classes/dbconnection.class.php");
include ("../classes/login.class.php");
if(isset($_POST["submitLogin"])) {
$studentNumber = $_POST["studentNumber"];
$studentClass = $_POST["studentClass"];
$dbConnection = new DatabaseConnection();
$login = new Login($dbConnection);
if($login->studentLogin($studentNumber, $studentClass)) {
echo "Succes";
}
else {
echo "Student not found!";
}
}
?>
<!DOCTYPE html>
<html class="no-js" lang="nl">
<head>
<meta charset="UTF-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="Communication Centre" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login Plansysteem Keuzetrainingen</title>
<link rel="icon" type="image/png" href="../img/favicon.png" sizes="16x16 32x32" />
<link rel="stylesheet" type="text/css" href="../css/foundation.css" />
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Advent+Pro" />
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<script type="text/javascript" src="../js/vendor/modernizr.js"></script>
</head>
<body>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<h1 class="mainTitle">inloggen</h1>
</div>
</div>
<form method="post">
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<small class="error"></small>
</div>
</div>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<div class="row collapse">
<div class="small-2 medium-1 large-1 columns">
<span class="prefix">
<img src="../img/cursor_icon.png" alt="Cursor Icon" />
</span>
</div>
<div class="small-10 medium-11 large-11 columns">
<input type="text" name="studentNumber" placeholder="Studentnummer" class="placeholderBlack" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<div class="row collapse">
<div class="small-2 medium-1 large-1 columns">
<span class="prefix">
<img src="../img/person_icon.png" alt="Person Icon" />
</span>
</div>
<div class="small-10 medium-11 large-11 columns">
<select name="studentClass">
<option value="">Selecteer Klas</option>
<option value="1DVTM-REG-01.P1">1DVTM-REG-01.P1</option>
<option value="1DVTM-REG-02.P1">1DVTM-REG-02.P1</option>
<option value="1DVTM-REG-03.P1">1DVTM-REG-03.P1</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="small-12 medium-8 medium-offset-2 large-6 large-offset-3 columns">
<input type="submit" name="submitLogin" value="Login" class="button expand buttonBlack" />
</div>
</div>
</form>
<script type="text/javascript" src="../js/vendor/jquery.js"></script>
<script type="text/javascript" src="../js/foundation.min.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
</body>
</html>
This looks quite a bit like the login system that I have built for my projects, as far as returning error messages, you can assign the error to a variable and use it with return to pass it along. Another thing that may be easier to do is to use an ajax call for the login instead of having the php directly on the page. This would also allow for you to dynamically assign error/success messages.
But as far as returning the error messages you could change the catch to something like this
$status = [];
if(!empty($selectStudentCheck)) {
status['status'] = true;
return status;
}
else {
$status['status'] = false;
$status['msg'] = "Studentnumber or class is not correct";
return $status;
}
this would also remove the need for the showErrorMessage() function. You would then to need to just check ['status'] and then display ['msg'] if you want to display the error. The above would also work well with an ajax call.
One other thing that I noticed that you may want to do is to move your database info into a separate file to be included so that you can set permission on it so that the info is more secure. Something I have done with mine is the following
db_info.inc
<?php
# Defining Database Values to avoid hardcoding in each file.
define ('DB_USER', 'user');
define ('DB_PASS', 'supersecret password');
define ('DB_HOST_WRITE', 'host1'); # Master DB
define ('DB_HOST_READ', 'host2'); # Slave DB
define ('DB_ONE', 'database1');
define ('DB_TWO', 'database2');
Then just include the the file and assign them to the variables you need and inset them where they need to be. such as below.
class User {
# Set class wide variables
private $db;
public $dbuser = DB_USER;
public $dbhost = DB_HOST_WRITE;
public $dbname = DB_ONE;
public $dbpass = DB_PASS;
Also you can construct the actual database connection inside the construct. of the actual login class so that you don't have to pass it into the login functions. This can also allow you to more easily assign database rights to users for special functions.
public function __construct() {
try {
$this->db = new PDO("mysql:host=" . $this->dbhost . ";dbname=" . $this->dbname, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
file_put_contents($this->pdolog, $ex->getMessage(), FILE_APPEND);
}
}
Hope this helps
==========
For the ajax call the blow is snippets from my own implementatation
the login form
<form id="formLogin">
<input class="form-control center-block text-center" name="username" id="username" placeholder="Username" type="text" required>
<input class="form-control center-block text-center" name="password" id="password" placeholder="Password" type="password" required>
<input type="button" value="Login" id="login" class="btn btn-block btn-primary center-block" onclick="userlogin(event, '#formLogin')">
</form>
The onlick option is the magic part. It calls the following jquery script.
function userlogin(event, loginform) {
event.preventDefault();
$('#login').fadeOut();
$.ajax({
type: 'POST',
url: '/inc/login.php',
data: $(loginform).serializeArray(),
dataType: 'json',
success: function(data) {
if (data.status == 'error') {
alert(data.statusmsg);
$('#login').fadeIn();
}
if (data.status == 'success') {
window.location = '/account/';
}
},
error: LogonError
});
}
function LogonError() {
alert('Error: The system could not log you in.' +
'\n\nIf you believe this is an error please email the' +
'\nAdministrator at admin#blacklistlogistics.com');
}
This takes the values from the form with jquery doing all the extra magix so I dont have to and passes it to the php page login.php
login.php
$user = #$_POST['username'];
$pass = #$_POST['password'];
$response = array();
if($user == null) {
$errors = 1;
$response['statusmsg'] .= "Please enter your username.\n";
}
if($pass == null) {
$errors = 1;
$response['statusmsg'] .= "Please enter your password.\n";
}
if($errors === 1) {
$response['status'] = 'error';
echo json_encode($response);
return;
} else {
$login = new User;
$loginstatus = $login->login($user, $pass);
if($loginstatus === 0) {
$response['status'] = 'error';
$response['statusmsg'] = "The system was unable to log you in. Please try again later.\nIf this error presists please inform the site administrator.";
echo json_encode($response);
return;
}
if($loginstatus === 2) {
$response['status'] = 'error';
$response['statusmsg'] = "There was an error. Please try again later.\nIf this error presists please inform the site administrator.";
echo json_encode($response);
return;
}
if($loginstatus === 1) {
$response['status'] = 'success';
echo json_encode($response);
return;
}
}
This grabs the info that jquery passed us out of the post and then passes it to the login function and then checks the return values and passes the info needed back to jquery to display errors etc.
the login function
public function login($username, $password) {
# Set login time
$logintime = date('Y-m-d H:i:s');
$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
# setting db connection inside try for exception handling
try {
$conn = $this->db;
$stmt = $conn->prepare('SELECT * FROM Members WHERE UserName = :username');
$stmt->execute(array(':username' => $username));
$results = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = NULL;
} catch (PDOException $ex) {
$conn = NULL;
file_put_contents($this->pdolog, $ex->getMessage(), FILE_APPEND);
return 2;
}
if ($results === FALSE || $results['AccountActive'] === 0) {
$conn = NULL;
return 0;
} else {
if (password_verify($password, $results['UserPass'])) {
try {
$stmt = $conn->prepare('UPDATE Members SET LastDate = :lastdate, LastIP = :lastip, FailCount = :failcount WHERE MemberID = :memberid');
$stmt->execute(array(':lastdate' => $logintime, ':lastip' => $ip, ':failcount' => 0, ':memberid' => $results['MemberID']));
} catch (PDOException $ex) {
$conn = NULL;
file_put_contents($this->pdolog, $ex->getMessage(), FILE_APPEND);
return 2;
}
$conn = NULL;
$_SESSION['login'] = 1;
$_SESSION['MemberID'] = $results['MemberID'];
$_SESSION['UserName'] = $results['UserName'];
return 1;
} else {
$conn = NULL;
return 0;
}
}
}
after the function has run and data has been passed back to the jquery call, jquery then process the data in the success or error portions.
Hope this helps as well, also sorry for the long copy/paste code. also I kept the majority of the extra peices of my code intact just incase you would like to pull ideas from it.
Related
i'm trying to make a OOP Login with ajax, but when I run it I can not get the session started or redirected to the "Directivo.php" page, i don't get any output, where should I start looking?
bdcon.php This is my database connection code
<?php
class Conexion extends mysqli{
private $DB_HOST = 'localhost';
private $DB_USER = 'root';
private $DB_PASS = '';
private $DB_NAME = 'bdhtav2';
public function __construct(){
parent:: __construct($this->DB_HOST, $this->DB_USER, $this->DB_PASS, $this->DB_NAME);
$this->set_charset('utf-8');
$this->connect_errno ? die('Error en la conexion'. mysqli_connect_errno()) :
$M = 'Conectado Correctamente';
echo $M;
}
}
?>
classuser.php Here I do the class that defines the operation of the login
<?php
require "bdcon.php";
session_start();
class Users
{
public $user;
public $pass;
public function __construct($usuario, $contraseña)
{
$this->user=$usuario;
$this->pass=$contraseña;
}
public function login()
{
$db = new Conexion();
$sql = "SELECT * from user where username = ".$this->user." and password = ".$this->pass; $query = $db->prepare($sql);
$stmt = $db->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($count == 1 && !empty($row)){
$_SESSION["USERNAME"] = $row["username"];
header('location: directivo.php');
}else{
echo"Error";
}
}
}
?>
acceso.php Here the inputs are filled and is sent through AJAX to "logeo.php"
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> Log-In </title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</head>
<body>
<!--Insentar navbar -->
<div class="container" style="margin-top:15%;">
<div class="row">
<div class="col">
</div>
<div class="col-md-7">
<H1 align="center">Inicio de Sesión</H1>
<h4 align="center">Directivos</h4>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Nombre de Usuario</span>
</div>
<input type="text" id="user1" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Contraseña</span>
</div>
<input type="text" id="pass1" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
</div>
<button type="button" id="enviar" class="btn btn-primary btn-lg">Iniciar Sesión</button>
<span id="Mensaje"></span>
<div class="col"></div>
</div>
</div>
<script>
$(document).ready(function(){
function getErrorMessage(jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#Mensaje').html(msg);
}
$('#enviar').click(function(){
var user1 = $('#user1').val();
var pass1 = $('#pass1').val();
$.ajax({
type:"POST",
url:"logeo.php",
data:{user:user1,pass:pass1},
dataType:"html",
success: function(response){
$("#Mensaje").val(response.responseText);
alert("Ya puedes dormir");
},
error: function(jqXHR, exception){
getErrorMessage(jqXHR, exception);
}
});
});
});
</script>
</body>
</html>
logeo.php Here i call the login() class and use the AJAX data
<?php
require 'classuser.php';
$usuario = $_POST["user"];
$contraseña = $_POST["pass"];
echo $usuario;
$logeo=new Users($usuario, $contraseña);
$logeo->login();
?>
A couple things. It looks like you are echoing your mysqli errors prior to starting your session. You session has to be set before anything gets outputted to the browser.
Here are my suggestions to fix your problem.
You Users class should not have anything in the file except the class. ie. No requires or session_starts().
In your case the Users class should extend the Conexion class.
Your session_start() should always be the first line in the initial PHP script. In your case the logeo.php script.
logeo.php
<?php
session_start(); //Always first line. Has to be set before anything is sent out to the browser.
require 'bdcon.php';
require 'classuser.php';
$usuario = $_POST["user"];
$contraseña = $_POST["pass"];
echo $usuario;
$logeo=new Users($usuario, $contraseña);
$logeo->login();
?>
classuser.php
class Users extends Conexion
{
public $user;
public $pass;
public function __construct($usuario, $contraseña)
{
$this->user=$usuario;
$this->pass=$contraseña;
}
public function login()
{
$db = new Conexion(); //By extending the class you would not need to make a new instance of the Conexion class.
$sql = "SELECT * from user where username = ".$this->user." and password = ".$this->pass;
$stmt = $db->prepare($sql); ////By extending your class this could be something like "$this->db->prepare($sql);"
$stmt->execute();
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($count == 1 && !empty($row)){
$_SESSION["USERNAME"] = $row["username"];
header('location: directivo.php');
}else{
echo"Error";
}
}
}
?>
That should get you going in the right direction. You may have to tinker around with your Conexion class to get it to work correctly.
I am currently building a small application to manage the amount of comic books I have at the present. I am using MVC in notepad++, I would have used a framework however it isn't a large application so didn't see the need of one. I am using PHP backend and Twitter Bootstrap as the front end however I am having a snag when logging in using Sessions. I have registered using the application which works no problem however when I try to login with the credentials it just keeps loading index.php instead of login.php.
View
header.phtml
<!DOCTYPE html>
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<html>
<head>
<link href="css/custom.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet">
<title>My Comics</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body onload="initialize()" style="background-color: #D3D3D3;">
<!-- If email is does not equal email in database then remain in index page -->
<?php if (isset($_SESSION['Email']) && $_SESSION['Email'] <> ''): ?>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<?php endif; ?>
<div class="container">
<!-- If email does equal the one given in database login to profile -->
<?php if (isset($_SESSION['Email'])): ?>
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<?php endif; ?>
<a class="navbar-brand" href="index.html">My Comics</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
</ul>
<!-- Display logout button along with users email -->
<?php if (isset($_SESSION['Email']) && $_SESSION['Email'] <> ''): ?>
<div class="navbar-search navbar-brand pull-right">
<?php if (isset($_SESSION['Email'])): ?>
<form action="logout.php" method="post">
<!-- Welcome message for user with logout button -->
<?php if ($_SESSION['Email'] != "") echo "Welcome " . $_SESSION['Email']; ?>
<input type="submit" value="Logout" name="submit" class="btn-danger"/>
</form>
<?php endif; ?>
</div>
</div>
<!-- Login Form for users -->
<?php else: ?>
<form class="navbar-form navbar-right" action="login.php" method="post">
<div class="form-group">
<input name="Email" value="Email" id="Email" type="text" class="form-control" placeholder="Enter Username">
</div>
<div class="form-group">
<input name="Password" value="Password" id="Password" type="password" class="form-control" placeholder="Enter Password">
</div>
<button name="submit" type="submit" name="submit" id="submit" class="btn btn-default">Login</button>
</form>
<?php endif; ?>
<!--/.nav-collapse -->
</div>
</div>
<div class="container">
Model
LoginData.php
<?php
class LoginData {
protected $Name, $Email, $Password;
public function __construct($dbrow) {
$this->Name = $dbrow['Name'];
$this->Email = $dbrow['Email'];
$this->Password = $dbrow['Password'];
}
function getName() {
return $this->Name;
}
function getEmail() {
return $this->Email;
}
function getPassword() {
return $this->Password;
}
function logout() {
$_SESSION = array();
session_destroy();
}
}
LoginDataSet.php
<?php
require_once('Model/Database.php');
require_once('Model/LoginData.php');
class LoginDataSet {
protected $_dbHandle, $_dbInstance = null;
public function __construct() {
$this->_dbInstance = Database::getInstance();
$this->_dbHandle = $this->_dbInstance->getdbConnection();
}
public function fetchLoginDetails($Email, $Password) {
$Password = crypt($Password, $Email);
$sqlQuery = "SELECT * FROM users WHERE Email=:u AND Password=:p"; //basic SQL Query
$statement = $this->_dbHandle->prepare($sqlQuery); //Prepare PDO statement
//SQL Injection
$statement->execute(array(
':u' => $Email,
':p' => $Password
)); //Executes PDO statement
$dataSet = [];
while ($row = $statement->fetch()) { //Fetches the next row matching the query
$dataSet[] = new LoginData($row);
}
return $dataSet;
}
public function fetchProfileDetails($Name) {
$sqlQuery = "SELECT * user WHERE Name='" . $Name . "'";
$statement = $this->_dbHandle->prepare($sqlQuery); //Prepare PDO statement
$statement->execute(); //Executes PDO statement
$dataSet = [];
while ($row = $statement->fetch()) { //Fetches the next row matching the query
$dataSet[] = new LoginData($row);
}
return $dataSet;
}
}
?>
Controller
<?php
//session start will always be an email
session_start();
$view = new stdClass();
$view->pageTitle = 'LoggedIn';
require_once ('Model/LoginDataSet.php');
//if submit is pressed
if (isset($_POST['submit'])) {
//check the email and password against the one in the database.
$LoginDataSet = new LoginDataSet();
//if email and password matches one in the database
$view->LoginDataSet = $LoginDataSet->fetchLoginDetails($_POST['Email'], $_POST['Password']);
//get the variables below using the functions of logindataset
if (count($view->LoginDataSet) == 1) {
$_SESSION['Email'] = $_POST['Email'];
$_SESSION['Name'] = $view->LoginDataSet[0]->getName();
//continue on to profile page
header("Location:home.php");
} else {
//if incorrect return to index page with error
$_SESSION['error'] = "logindetails";
header("Location:index.php");
}
}
require_once('View/home.phtml');
This is what it looks like at the present
This is what it should look like
I had designed the website first in HTML and then dynamically in PHP which I usually do. However it isn't going to the login.php controller it just keeps refreshing index.php, Is there anything particular that anyone notices that could rectify this so it does login and also that doesn't get rid of the Name of the application and button ?
Any help would be greatly appreciated.
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);
At the moment I have a form (PHP & jQuery) with validations. I want to add a validation to check if the email address of a new user is already in the MySQL database or not.
At the moment there are 3 (IF) validations already for the name and email in jQuery:
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
I would like to have a 4th one to check if the email address is already in the MySQL database.
The complete PHP file with jQuery:
<?php
include 'db_connection.php';
if(isset($_POST['finish'])){
$name = '"'.$dbConnection->real_escape_string($_POST['name']).'"';
$email = '"'.$dbConnection->real_escape_string($_POST['email']).'"';
$password = '"'.password_hash($dbConnection->real_escape_string($_POST['password']), PASSWORD_DEFAULT).'"';
$gender = '"'.$dbConnection->real_escape_string($_POST['gender']).'"';
$sqlInsertUser = $dbConnection->query("INSERT INTO users (name, password, email, gender) VALUES($name, $password, $email, $gender)");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/text.css" />
<link rel="stylesheet" href="css/960.css" />
<link rel="stylesheet" href="css/demo.css" />
<script src="scripts/jquery-1.10.2.js"></script>
<style>
CSS CODE
</style>
<script>
function validate() {
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none') {
if(!($("#name").val())) {
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val())) {
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#email-error").html("Invalid Email!");
output = false;
}
}
if($("#password-field").css('display') != 'none') {
if(!($("#user-password").val())) {
output = false;
$("#password-error").html("Password required!");
}
if(!($("#confirm-password").val())) {
output = false;
$("#confirm-password-error").html("Confirm password required!");
}
if($("#user-password").val() != $("#confirm-password").val()) {
output = false;
$("#confirm-password-error").html("Password not matched!");
}
}
return output;
}
$(document).ready(function() {
$("#next").click(function(){
var output = validate();
if(output) {
var current = $(".active");
var next = $(".active").next("li");
if(next.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+next.attr("id")+"-field").show();
$("#back").show();
$("#finish").hide();
$(".active").removeClass("active");
next.addClass("active");
if($(".active").attr("id") == $("li").last().attr("id")) {
$("#next").hide();
$("#finish").show();
}
}
}
});
$("#back").click(function(){
var current = $(".active");
var prev = $(".active").prev("li");
if(prev.length>0) {
$("#"+current.attr("id")+"-field").hide();
$("#"+prev.attr("id")+"-field").show();
$("#next").show();
$("#finish").hide();
$(".active").removeClass("active");
prev.addClass("active");
if($(".active").attr("id") == $("li").first().attr("id")) {
$("#back").hide();
}
}
});
});
</script>
</head>
<body>
<div class="container_12">
<div class="grid_8">
<p>
TEXT<br>TEXT<br>TEXT<br>TEXT<br>TEXT
</p>
</div>
<div class="grid_4">
<p>Register new FC Magnate</p>
<div class="message"><?php if(isset($message)) echo $message; ?></div>
<ul id="signup-step">
<li id="personal" class="active">Personal Detail</li>
<li id="password">Password</li>
<li id="general">General</li>
</ul>
<form name="frmRegistration" id="signup-form" method="post">
<div id="personal-field">
<label>Name</label><span id="name-error" class="signup-error"></span>
<div><input type="text" name="name" id="name" class="demoInputBox"/></div>
<label>Email</label><span id="email-error" class="signup-error"></span>
<div><input type="text" name="email" id="email" class="demoInputBox" /></div>
</div>
<div id="password-field" style="display:none;">
<label>Enter Password</label><span id="password-error" class="signup-error"></span>
<div><input type="password" name="password" id="user-password" class="demoInputBox" /></div>
<label>Re-enter Password</label><span id="confirm-password-error" class="signup-error"></span>
<div><input type="password" name="confirm-password" id="confirm-password" class="demoInputBox" /></div>
</div>
<div id="general-field" style="display:none;">
<label>Gender</label>
<div>
<select name="gender" id="gender" class="demoInputBox">
<option value="female">Female</option>
<option value="male">Male</option>
</select></div>
</div>
<div>
<input class="btnAction" type="button" name="back" id="back" value="Back" style="display:none;">
<input class="btnAction" type="button" name="next" id="next" value="Next" >
<input class="btnAction" type="submit" name="finish" id="finish" value="Finish" style="display:none;">
</div>
</form>
</div>
The "db_connection.php" file:
<?php
define('_HOST_NAME', 'localhost');
define('_DATABASE_USER_NAME', 'root');
define('_DATABASE_PASSWORD', '****');
define('_DATABASE_NAME', '****');
$dbConnection = new mysqli(_HOST_NAME, _DATABASE_USER_NAME, _DATABASE_PASSWORD, _DATABASE_NAME);
if ($dbConnection->connect_error) {
trigger_error('Connection Failed: ' . $dbConnection->connect_error, E_USER_ERROR);
}
?>
I tried to create this validation from other examples that were given here on the website. But, no success. Please, it would be great if somebody could help me a little further.
UPDATE: With the help of Suyog I changed the files. But, it doesn't seem to work yet. Here are the files that I use at the moment: fcmagnate.com/files.zip
The form works till the moment the validation of the email address in the database starts, than it stops.
You will have to make use of JQuery AJAX for this.
Write a function in AJAX to send email to php gage where we will check the existance of email.
<script>
function checkEmail(eMail)
{
$.ajax({
url: 'check_email.php',
data: {emailId: eMail},
type: 'post',
success: function (data) {
if(data == '1')
return false;
else
return true;
}
});
}
</script>
Then you can call this function
<script>
function validate()
{
var output = true;
$(".signup-error").html('');
if($("#personal-field").css('display') != 'none')
{
if(!($("#name").val()))
{
output = false;
$("#name-error").html("Name required!");
}
if(!($("#email").val()))
{
output = false;
$("#email-error").html("Email required!");
}
if(!$("#email").val().match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#email-error").html("Invalid Email!");
output = false;
}
if(!checkEmail($("#email").val()))
{
$("#email-error").html("Email already exist!");
output = false;
}
}
}
</script>
Youe check_email.php file will contain the code as follows
<?php
include 'db_connection.php';
if(isset($_POST['emailId']))
{
$email = '"'.$dbConnection->real_escape_string($_POST['emailId']).'"';
$sqlCheckEmail = $dbConnection->query("SELECT user_id FROM users WHERE LOWER(email) like LOWER('%".$email."%')");
if($sqlCheckEmail->num_rows == 1)
echo '1';
else
echo '0';
}
?>
Use Ajax jQuery.ajax on client side to communicate with server side reusing your php code mentioned.
i'm trying to create a simple user class but i can't get the data in the database i tried a lot of different code now here is the user class
namespace MonetizeMedia;
class User {
private $uid;
private $fields;
public function __construct() {
$this->uid = null;
$this->fields = array('username' => '',
'password' => '');
}
public function __get($field) {
if($field == 'uid')
{
return $this->uid;
}
else
{
return $this->fields[$field];
}
}
public function __set($field, $value) {
if(array_key_exists($field, $this->fields))
{
$this->fields[$field] = $value;
}
}
public function createUser() {
try {
$db = new \MonetizeMedia\Database;
$bcrypt = new \MonetizeMedia\Bcrypt(15);
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->bindParam(":password", $bcrypt->hash($password));
$stmt->execute();
return "Registration Successful";
} catch ( PDOException $e ) {
return $e->getMessage();
}
}
and here is the register page
<?php
ob_start();
session_start();
include 'classes/user.class.php';
if(isset($_POST['submitted'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$User->username = $username;
$User->password = $password;
if($User->createUser()) {
echo "DONE!";
}
else
{
echo "An error occured while creating your account. Please try later.";
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Register</title>
</head>
<body>
<form method="post" action="">
<ul>
<li>
<label for="usn">Username : </label>
<input type="text" name="username" />
</li>
<li>
<label for="passwd">Password : </label>
<input type="password" name="password" />
</li>
<li class="buttons">
<input type="submit" name="register" value="Register" />
</li>
</ul>
</form>
</body>
</html>
i'm trying to learn php and pdo so i'm not so good at the moment