PDO Simple User Class Wont Work - php

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

Related

How To Use Getters And Setters In PHP With User Input

I have created a registration form and now I want to insert data by using Getters and Setters. I have created intAll.php file which has HTML structure and PHP function, then I have created Encap.php file which has Database Connection, My SQL Queries and Getters/Setters. Now I want to pass my Input Data to Encap.php file and I want to catch them in Encap.php file and insert into My SQL DB, but my codes don't work.
So, How to Fix this?
intAll.php File
<?php
include 'Encap.php';
$InsertData = new Databases;
$success_message = '';
if(isset($_POST["submit"]))
{
$InsertData->setName($_POST['name']);
$InsertData->setUsername($_POST['username']);
$InsertData->setPassword($_POST['password']);
//$name=$_POST['name'];
//$username=$_POST['username'];
//$password=$_POST['password'];
if($InsertData->insertsingle())
{
$success_message = 'Post Inserted';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Insert data into Table using OOPS in PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:700px;">
<form method="post">
<label>Name</label>
<input type="text" name="name" class="form-control" />
<br />
<label>Username</label>
<input type="text" name="username" class="form-control" />
<br />
<label>Password</label>
<input type="text" name="password" class="form-control" />
<br />
<input type="submit" name="submit" class="btn btn-info" value="Submit" />
<span class="text-success">
<?php
if(isset($success_message))
{
echo $success_message;
}
?>
</span>
</form>
</div>
</body>
</html>
Encap.php File
<?php
class Databases{
public $con;
private $id;
private $name;
private $username;
private $password;
function setId($id) {
$this->id = $id;
}
function getId() {
return $this->id;
}
function setName($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
function setUsername($username) {
$this->username = $username;
}
function getUsername() {
return $this->username;
}
function setPassword($password) {
$this->password = $password;
}
function getPassword() {
return $this->password;
}
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "portal");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES ('getName()','getUserName()','getPassword()')";
$rsint=mysqli_query($this->con, $string);
return $rsint;
}
}
?>
You cannot call a function within in a string. You should interrupt your string to do that:
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES ('" . $this->getName() . "','" . $this->getUserName() . "','" . $this->getPassword() . "')";
$rsint=mysqli_query($this->con, $string);
return $rsint;
}
However, since you're not sanitizing your user input anywhere, this code is vulnerable to SQL injection attacks and you should be using a prepared statement instead (note: untested code, might need to be tweaked a little):
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($this->con, $string);
$stmt->bind_param("sss", $this->getName(), $this->getUserName(), $this->getPassword());
$rsint = $stmt->execute();
return $rsint;
}

PHP - Login Page

We both thought it was working but I tested it and it doesnt output anything. It checks if theres sessions e.t.c and if not then its meant to output a form but it doesnt can anyone enlighten me on my error?
Code:
<?php
session_start();
//Include Database Config.
include('../cdn/global/db.php');
//PDO Settings.
$opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
$dsn = "mysql:host=$host;dbname=$dbname";
//Create a PDO Session.
$DBH = new PDO($dsn, $username, $password, $opt);
//Session Attributes.
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$loginForm = "
<form method='POST' action='' class='pure-form' style='color: #000;'>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>'
</fieldset>
</form>";
if(isset($_POST['username']) && isset($_POST['password'])){
echo $_POST['username'].'is trying to login with password'.$_POST['password'];
$st = $DBH->prepare("SELECT :username FROM users WHERE username = :username AND password = :password");
$st->bindParam(':password', $_POST['password']);
$st->bindParam(':username', $_POST['username']);
$st->execute();
if($st->rowCount()){
$row = $st->fetch(PDO::FETCH_OBJ);
$_SESSION['username'] = $row->username;
echo $_SESSION['username'];
return true;
}
} else if(!isset($_SESSION['username'])) {
echo $loginForm;
}
?>
I think your problem will be resolved if you remove the isset from the first two lines so your first lines should look as follow:
if(!$_SESSION['username'] && ! $_POST['username'] && ! $_POST['password']) {
echo $loginForm;
} elseif(isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['password'])) {
$grantAccess = login(); //after some serious validation or validate inside
if(!$grantAccess) {
echo 'Test 2';
}
}
Personally, I try to separate tasks so I can keep things straight. Here is basically what I do. Note, all the functions would be on their own files included as needed into any pages that require them. I have notated areas of interest:
<?php
session_start();
// This would be better as a static class so as not to create new connections all the time
// You can populate all the false values here with actual database info
// If you do it here, then the function will not need arguments when you go
// To use it. The only time you would populate the args after this point is if
// you need to connect to multiple databases on the same page.
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
// Include Database Config.
// If you just have $username,$password,$host,$dbname here,
// you can skip this if you just add those values into the Connect()
// function as default arguements
include('../cdn/global/db.php');
//Add static function that listens for logout
user_logout();
// If username set (password is also going to be set)
if(!empty($_POST['username']))
// Get true/false for user hit
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
// If there is no session username, show login form
echo (empty($_SESSION['username']))? LoginForm() : 'Log Out';
?>
EDIT: How I would do it in this scenario (in a general sense)
/functions/functions.php
<?php
function Connect($host = false,$username = false,$password = false,$dbname = false)
{
try {
//Create a PDO Session.
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password,array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
//Session Attributes.
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $e) {
echo "<code><pre>".print_r($e)."</pre></code>";
$con = false;
}
return $con;
}
// Since you are just assigning a variable some html, may as well make it a bit flexible in a function (just incase)
function LoginForm($settings = false)
{
$method = (!empty($settings['method']))? $settings['method']:"post";
$action = (!empty($settings['action']))? $settings['action']:"";
$id = (!empty($settings['id']))? ' id="'.$settings['id'].'"':"";
$class = (!empty($settings['class']))? $settings['class']:"pure-form";
ob_start();
?>
<form method='<?php echo $method; ?>' action='<?php echo $action; ?>' class='<?php echo $class; ?>' style='color: #000;'<?php echo $id; ?>>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>
</fieldset>
</form>
<?php
$data = ob_get_contents();
ob_end_clean();
return $data;
}
function fetch($sql = false,$bind = false,$obj = false)
{
if(empty($sql))
return 0;
$query = Connect()->prepare($sql);
if(!$query)
return 0;
$query->execute($bind);
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
if(!empty($row))
$row = ($obj)? (object) $row : $row;
else
$row = 0;
return $row;
}
function user_login($username = false, $password = false)
{
$st = fetch("SELECT username,password FROM users WHERE username = :username",array(":username"=>$username));
$valid = false;
if($st != 0) {
if($st[0]['password'] == $password) {
$_SESSION['username'] = $row[0]['username'];
$valid = true;
}
}
return $valid;
}
function user_logout($location = 'loggedout.php')
{
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
session_destroy();
header("Location: ".$location);
exit;
}
}
?>
login.php
session_start();
include_once(__DIR__.'/functions/functions.php');
user_logout();
?><html>
<head>
</head>
<body>
<?php
if(!empty($_POST['username']))
echo (user_login($_POST['username'],$_POST['password']))? "Welcome ".htmlspecialchars($_SESSION['username']) : "Invalid username and/or password!";
echo (empty($_SESSION['username']))? LoginForm() : 'Log Out';
?>
</body>
</html>
You can also create a class to manager your users. Let's create db.php class.
<?php
class Db {
private static $_dbase = 'data';
private static $_username = 'root';
private static $_passwd = '';
private static $_host = 'localhost';
private static $_options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
private static $_dsn;
private static $_db;
function __construct() {
}
public static function getDB() {
if (!isset(self::$_db)) {
try {
self::$_dsn = 'mysql:host=' . self::$_host . ';dbname=' . self::$_dbase;
self::$_db = new PDO(self::$_dsn, self::$_username, self::$_passwd, self::$_options);
} catch (PDOException $exc) {
echo $exc->getMessage();
}
}
return self::$_db;
}
}
And now let's create User.php class
<?php
session_start();
require_once 'db.php';
class USER {
private $db;
function __construct() {
$this->db = Db::getDb();
}
public function register($uname, $umail, $upass) {
try {
$new_password = password_hash($upass, PASSWORD_DEFAULT);
//create the activasion code
$activation = md5(uniqid(rand(), true));
$stmt = $this->db->prepare("INSERT INTO users(user_name,user_email,user_pass,active)
VALUES(:uname, :umail, :upass,:active)");
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);
$stmt->bindparam(":active", $activation);
$stmt->execute();
$id = $this->db->lastInsertId('memberID');
$this->sendMail($id, $activation);
$this->redirect('sign-up.php?joined');
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 AND `user_email` = :umail LIMIT 1");
$stmt->execute(array(':uname' => $uname, ':umail' => $umail));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
//verifying user.
if (password_verify($upass, $userRow['user_pass']) && $userRow['active'] === 'Yes') {
$_SESSION['user_session'] = $userRow['user_id'];
return true;
} else {
return false;
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
private function sendMail($email,$id, $activation) {
//send email to the user for account activation.
$to = $email;
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n " . DIR . "activate.php?x=$id&y=$activation\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <" . SITEEMAIL . ">\r\n";
$additionalheaders .= "Reply-To: " . SITEEMAIL . "";
mail($to, $subject, $body, $additionalheaders);
}
//check if the user is logged in
public function is_loggedin() {
if (isset($_SESSION['user_session'])) {
return true;
}
}
// redirect the user.
public function redirect($url) {
header("Location: $url");
}
//user log out
public function logout() {
session_destroy();
unset($_SESSION['user_session']);
return true;
}
//display login form
public function display_login_form() {
return "
<form method='POST' action='' class='pure-form' style='color: #000;'>
<fieldset class='pure-group'>
<input type='text' name='username' style='display: inline-block;' class='pure-input-1-2' placeholder='Username'><br>
</fieldset>
<fieldset class='pure-group'>
<input type='password' name='password' style='display: inline-block;' class='pure-input-1-2' placeholder='Password'><br>
</fieldset>
<fieldset class='pure-group'>
<button type='submit' style='display: inline-block;' class='pure-button pure-input-1-2 pure-button-primary'>Login</button>'
</fieldset>
</form>";
}
}
We are going to check if the user is logged in and if not display the login form.
<?php
require_once 'User.php';
$User = new User();
$form = '';
if($User->is_loggedin()){
$User->redirect('private.php');
}else{
$form = $User->display_login_form();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><?php echo $form; ?></div>
</body>

PHP OOP PDO Error Display

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.

Registration page not processing data to database

I am developing a website with User registration and login ,after completing the page configuration ,i tried to register it worked perfectly and later next day i tried to register but the page is not loading ,after filling in the data and if i click submit ,it reloads the same register page with no effect ,how to solve this problem
SQL Query Processing code: (class.newuser.php)
enter code here
class User
{
public $user_active = 0;
private $clean_email;
public $status = false;
private $clean_password;
private $clean_username;
private $unclean_username;
public $sql_failure = false;
public $mail_failure = false;
public $email_taken = false;
public $username_taken = false;
public $activation_token = 0;
function __construct($user,$pass,$email)
{
//Used for display only
$this->unclean_username = $user;
//Sanitize
$this->clean_email = sanitize($email);
$this->clean_password = trim($pass);
$this->clean_username = sanitize($user);
if(usernameExists($this->clean_username))
{
$this->username_taken = true;
}
else if(emailExists($this->clean_email))
{
$this->email_taken = true;
}
else
{
//No problems have been found.
$this->status = true;
}
}
public function userPieAddUser()
{
global $db,$emailActivation,$websiteUrl,$db_table_prefix;
//Prevent this function being called if there were construction errors
if($this->status)
{
//Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
//Construct a unique activation token
$this->activation_token = generateactivationtoken();
//Do we need to send out an activation email?
if($emailActivation)
{
//User must activate their account first
$this->user_active = 0;
$mail = new userPieMail();
//Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE",array("{$websiteUrl}/",$this->activation_token));
//Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array("#ACTIVATION-MESSAGE","#ACTIVATION-KEY","#USERNAME#"),
"subjectStrs" => array($activation_message,$this->activation_token,$this->unclean_username)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if(!$mail->newTemplateMsg("new-registration.txt",$hooks))
{
$this->mail_failure = true;
}
else
{
//Send the mail. Specify users email here and subject.
//SendMail can have a third parementer for message if you do not wish to build a template.
if(!$mail->sendMail($this->clean_email,"New User"))
{
$this->mail_failure = true;
}
}
}
else
{
//Instant account activation
$this->user_active = 1;
}
if(!$this->mail_failure)
{
//Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `".$db_table_prefix."users` (
`username`,
`username_clean`,
`password`,
`email`,
`activationtoken`,
`last_activation_request`,
`LostpasswordRequest`,
`active`,
`group_id`,
`sign_up_date`,
`last_sign_in`
)
VALUES (
'".$db->sql_escape($this->unclean_username)."',
'".$db->sql_escape($this->clean_username)."',
'".$secure_pass."',
'".$db->sql_escape($this->clean_email)."',
'".$this->activation_token."',
'".time()."',
'0',
'".$this->user_active."',
'1',
'".time()."',
'0'
)";
return $db->sql_query($sql);
}
}
}
}
?>
HTML register.php
enter code here
<?php
require_once("models/config.php");
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: index.php"); die(); }
?>
<?php
//Forms posted
if(!empty($_POST))
{
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
//Perform some validation
//Feel free to edit / change as required
if(minMaxRange(5,25,$username))
{
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(5,25));
}
if(minMaxRange(8,50,$password) && minMaxRange(8,50,$confirm_pass))
{
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT",array(8,50));
}
else if($password != $confirm_pass)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if(!isValidemail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
//End data validation
if(count($errors) == 0)
{
//Construct a user object
$user = new User($username,$password,$email);
//Checking this flag tells us whether there were any errors such as possible data duplication occured
if(!$user->status)
{
if($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE",array($username));
if($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE",array($email));
}
else
{
if(!$user->userPieAddUser())
{
if($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if(count($errors) == 0)
{
if($emailActivation)
{
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
} else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration | <?php echo $websiteName; ?> </title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>Sign Up</h2>
</div>
<div class="modal-body">
<div id="success">
<p><?php echo $message ?></p>
</div>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label>Re-type Password:</label>
<input type="password" name="passwordc" />
</p>
<p>
<label>Email:</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear"></div>
<p style="margin-top:30px; text-align:center;">Login / Forgot Password? / Home Page</p>
</body>
</html>
Its all due to div tags:
2 divisions closed within the form tag but they are opened outside the form tag.
So try by enclosing the whole form within one div(regbox) Including submit.
And make sure that no div is closed within form tag which is opened outside form tag.

PHP not displaying data from database

I am trying to display a list of comments from a MySql database in PHP.
The foreach loop works as it displays the necessary html for each comment in the database, but no actual content from the database is being pulled through.
Comment class
class Comment {
protected $_id;
protected $_user;
protected $_commentText;
protected $_dateTimePosted;
public function __construct()
{
$this->_dateTimePosted = new DateTime();
$this->_dateTimePosted->format(DATE_RFC3339);
}
public function get_id()
{
return $this->_id;
}
public function set_id($value)
{
$this->_id = $value;
}
public function get_user()
{
return $this->_user;
}
public function set_user($value)
{
$this->_user = $value;
}
public function get_commentText()
{
return $this->_commentText;
}
public function set_commentText($value)
{
$this->_commentText = $value;
}
public function get_dateTimePosted()
{
return $this->_dateTimePosted;
}
public function set_dateTimePosted($value)
{
$this->_dateTimePosted = $value;
}
}
CommentFunctions.php
include 'dbConnect.php';
class CommentFunctions {
protected $conn;
public function __construct()
{
$this->conn = dbConnect();
}
public function get_comments()
{
$sql = "SELECT * FROM comments";
$stmt = $this->conn->stmt_init();
$stmt->prepare($sql);
$stmt->execute();
$stmt->store_result();
$comments = array();
while ($row = $stmt->fetch())
{
$comment = new Comment();
$comment->set_id($row['id']);
$comment->set_user($row['user']);
$comment->set_commentText($row['comment_text']);
$comment->set_dateTimePosted($row['datetime_posted']);
$comments[] = $comment;
}
return $comments;
}
}
Index.php
<?php
include './includes/Comment.php';
include './includes/CommentFunctions.php';
$comments_func = new CommentFunctions();
$all_comments = $comments_func->get_comments();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Comments</title>
<link rel="stylesheet" type="text/css" href="./css/Master.css" />
<link rel="stylesheet" type="text/css" href="./css/Site.css" />
</head>
<body>
<div id="Container">
<h2>Comments</h2>
<a class="reload-comments" href="/">Refresh</a>
<div id="Comments">
<?php if (!$all_comments) {
echo 'No comments yet.';
} ?>
<?php foreach ($all_comments as $c) { ?>
<div class="comment">
<input class="id" type="hidden" value="<?php echo $c->get_id(); ?>" />
<div class="author">Posted by <?php echo $c->get_user(); ?></div>
<div class="comment-text">
Posted <?php echo $c->get_dateTimePosted(); ?>
<p><?php echo $c->get_commentText(); ?></p>
</div>
</div>
<?php } ?>
</div>
<div id="AddComment">
<form name="add_comment_form" id="add_comment_form" action="index.php" method="post">
<label for="user">Your Name:</label>
<input name="user" id="user" type="text" /><br />
<label for="comment_text">Comment:</label>
<textarea name="comment_text" id="comment_text" rows="5" cols="10"></textarea><br />
<input name="submit" id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" class="hidden" />
</form>
</div>
<div class="loader"></div>
<div class="response"></div>
</div>
</body>
Comments can be added, the data is stored fine in the database, and the loop runs the correct number of times, but the code such as echo $c->get_commentText(); is not displaying a value.
Appreciate any help.
Looks like you're using mysqli.
You're forgetting a key step: binding your result variables.
See http://www.php.net/manual/en/mysqli-stmt.bind-result.php and the examples there for more info on how to get actual values back.
try a
var_dump($all_comments)
after you fetch it, to prove that there is actually something in the array
next step would be to check that the sql worked. I am not sure what database layer you are using so i'm not sure what the check to do that would be.
i would assume that this method should have a return value you can check
$stmt->execute();

Categories