After submitting my form below via ajax the message always comes back as failed, even with the correct login information! I've coded this in a non oop style too and it works perfectly, but when i use this style of code it hangs up. The live site is http://andyholmes.me/demo/summersproperty/OOP/login.php and the username is admin#summersproperty.com and password is admin
login.php -
<?PHP
session_start();
include('includes/class.login.php');
$login = new Login();
$token = $_SESSION['token'] = md5(uniqid(mt_rand(), true));
if ($_POST['ajax']) {
exit($login->getStatus());
}
?>
<style>
#message { display: none; cursor: pointer; }
.loader { display: none; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(e) {
$(this).fadeOut(300);
$('.loader').delay(300).fadeIn(100);
$.post("<?=$_SERVER['PHP_SELF'];?>", { username: $('#username').val(), password: $('#password').val(), ajax: true }).done(function(data) {
if (data.logged_in == true) {
// Redirect with javascript
$('.loader').delay(2000).fadeOut(100);
$('#message').html('<p>Success! We\'ll redirect you in a minute...</p>').delay(2200).fadeIn(200);
} else {
$('.loader').delay(2000).fadeOut(100);
$('#message').html('<p>Failed... Click to try again!').delay(2200).fadeIn(200);
$('#message').on('click', function(){
$(this).fadeOut(200);
$('#loginForm').delay(350).fadeIn(200);
});
}
});
return false;
});
});
</script>
<form id="loginForm" method="POST" action="">
<table>
<tr><td>Username:</td><td><input type="text" name="username" id="username"/></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" id="password"/></td></tr>
</table>
<input type="hidden" name="token" value="<?=$token;?>"/>
<input type="submit" name="login" value="Log In"/>
</form>
<div class="loader">
<img src="loader.gif"/>
</div>
<div id="message"></div>
and the login class -
<?PHP
class Login
{
private $_id;
private $_username;
private $_password;
private $_passmd5;
private $_errors;
private $_access;
private $_login;
private $_token;
public function __construct()
{
$this->_errors = array();
$this->_login = isset($_POST['login']) ? 1 : 0;
$this->_access = 0;
$this->_token = $_POST['token'];
$this->_id = 0;
$this->_username = ($this->_login) ? $this->filter($_POST['username']) : $_SESSION['username'];
$this->_password = ($this->_login) ? $this->filter($_POST['password']) : '';
$this->_passmd5 = ($this->_login) ? md5($this->_password) : $_SESSION['password'];
}
public function isLoggedIn()
{
($this->_login) ? $this->verifyPost() : $this->verifySession();
return $this->_access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifyPost()
{
try
{
if(!$this->isTokenValid())
throw new Exception('Invalid form submission');
if(!$this->isDataValid())
throw new Exception('Invalid form data entered');
if(!$this->verifyDatabase())
throw new Exception('Invalid username/password combination');
$this->_access = 1;
$this->registerSession();
}
catch(Exception $e)
{
$this->_errors[] = $e->getMessage();
}
}
public function verifySession()
{
if($this->sessionExist() && $this->verifyDatabase())
$this->_access = 1;
}
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT user_id FROM users WHERE user_username = '{$this->_username}' AND user_password = '{$this->_passmd5}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
public function isDataValid()
{
return (preg_match('/^[a-zA-Z0-9]/', $this->_username) && preg_match('/^[a-zA-Z0-9]/', $this->_password)) ? 1 : 0;
}
public function isTokenValid()
{
return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token']) ? 0 : 1;
}
public function registerSession()
{
$_SESSION['id'] = $this->_id;
$_SESSION['username'] = $this->_username;
$_SESSION['password'] = $this->_passmd5;
}
public function sessionExist()
{
return (isset($_SESSION['username']) && isset($_SESSION['password'])) ? 1 : 0;
}
public function showErrors()
{
echo "<h3>Errors</h3>";
foreach($this->_errors as $key=>$value)
echo $value."<br>";
}
public function getStatus()
{
return json_encode(array('logged_in' => $this->isLoggedIn(), 'errors' => $this->showErrors()));
}
}
?>
By the way, i know i need to use PDOs etc, but i just want to get the script to a point where it works nicely before i change the database connection data. I know im close, but its really frustrating!
If you can help me, i will be most grateful!
EDIT NOTES: This code has been updated for an issue that has come up after using the suggestion from user1781670
<?PHP
session_start();
include('includes/class.login.php');
$login = new Login();
$token = $_SESSION['token'] = md5(uniqid(mt_rand(), true));
if ($_POST['ajax']) {
exit($login->getStatus());
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(e) {
$.post("<?=$_SERVER['PHP_SELF'];?>", { username: $('#username').val(), password: $('#password').val(), ajax: true }).done(function(data) {
if (data.logged_in == true) {
// Redirect with javascript
} else {
// Inject errors to html
// data.errors
}
});
return false;
});
});
</script>
<form id="loginForm" method="POST" action="">
<table>
<tr><td>Username:</td><td><input type="text" name="username" id="username"/></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" id="password"/></td></tr>
</table>
<input type="hidden" name="token" value="<?=$token;?>"/>
<input type="submit" name="login" value="Log In"/>
</form>
As you can see I modified your jquery removing you PHP code inside because that's not the place where it goes, also I changed the syntax a little to one more clear at least for me. Also note that "data" is a json returned by your PHP function getStatus who returns the login status as json.
Now you just need to create the PHP function that return the json. Maybe can help you to checkout json_encode. If you get stuck please tell us.
Example of getStatus function:
JavaScript objects are like associate arrays in PHP except JavaScript objects can have functions. So, is not surprise you need to pass an associative array to json_encode.
public function getStatus()
{
return json_encode(array('logged_in' => $this->isLoggedIn(), 'errors' => $this->showErrors()));
}
$.post automatically knows it received a JSON (it's the default option), so you can access it's properties with data.logged_in and data.errors.
This is the problem: you show your login form and when the user submit the form, through ajax you open a connection and send the data entered by the user and you expect the server to return information. But how is that data gonna be returned? how are you gonna handle it? well, that is JSON for. It's a syntax to write JavaScript objects, so with json_encode you return a JSON and when your JavaScript receives that JSON you can access it's data and check if it was a successful login.
Related
Currently, we are building a project about website blocking and I just have a few questions about php and how phpmyadmin reacts to certain actions. I am using wampserver
signup.php apparently shows no errors when inputting a new account, the username and password is supposed to be saved in the database.
Here it is:
<?php
require_once ("functions.php");
require_once ('config.php');
require_once ('User.php');
require_once ('Session.php');
$default_label = 0;
$error = null;
if($session->isLoggedIn()){
redirectTo("home.php");
}
if(requestIsPost()) {
global $session;
$params = requiredPostParams(['username' , 'password' , 'label'] , $strict=true);
if($params != null){
$default_label = $params['label'];
// put the data into data base and redirect to login
$ouser = User::findByUsername($params['username']);
if($ouser == null) {
try{
$nuser = new User();
$nuser->initialize($params['username'] , $params['password'] , $params['label']);
$nuser->save();
// everything is set, train the recognizer
$faceLIb = new COM($LIB_CLSID);
$nextDir = $unused_face_dir."/s".(string) $default_label;
$nextDirDest = $face_dir."/s".(string) $default_label;
rename($nextDir , $nextDirDest); // move directory into usable faces
$faceLIb->train($face_dir , $rec_path);
redirectTo("login.php");
} catch (InvalidUserData $iud) {
$error = "Invalid user data. Try Again";
} catch (DBQueryException $dbe) {
$error = "Application Error. Try Again";
} catch (DBConnectException $dce) {
$error = "Application error. Try Again";
}
} else {
$error = "Email alredy registered";
}
}
}
?>
<html>
<head>
<title>Signup</title>
</head>
<body>
<?php if($error != null) echo $error; ?>
<form action="" method="post" id = "dataform">
Email: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="hidden" name="label" id = "label" value = <?php echo '"'.$default_label.'"'; ?> >
<input type="button" value="Submit" id="submit_form">
</form>
<!-- the video scanner -->
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480" style = "display:none"></canvas>
<h1 id="status"></h1>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script>
// test if the camera is available
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
// event handlers
$("#snap").on("click" , function(){
train = function(){
$.ajax({
type: "GET",
url: "train.php",
data: "{}",
dataType: 'json',
success: function(result){
console.log(result);
if(result.code == 1) {
$("#label").val(result.label);
$("#status").text("Succesful");
}
else alert("Face detection Failed! Try again");
}
});
}
// send an image to the server, on sucess call recursive. do it 'i' times
send_images = function(i){
if( i === 0 ) {
$("#status").text("submitting ...");
train();
return;
}
$("#status").text(i);
// extract an image from the live camera
context.drawImage(video, 0, 0, 640, 480);
var url = canvas.toDataURL('image/png');
$.ajax({
type: "POST",
url: "upload.php",
//dataType: 'jsonp',
data: {
"url" : url
},
success: function(result){
send_images(i-1);
}
});
}
$.ajax({
type: "GET",
url: "ready.php",
success: function(result){
console.log(result);
}
});
send_images(10);
});
$("#submit_form").on("click" , function(){
var label = parseInt($("#label").val());
if(label < 1) alert("User saved. Use Snap photo to train image.");
else $('form#dataform').submit();
});
</script>
</body>
</html>
<?php
require_once("config.php");
require_once("SQLTable.php");
require_once("Validator.php");
require_once("Texter.php");
require_once("exceptions.php");
class User extends SQLTable{
/**
* #Overridden properties
*/
protected static $tableName = 'users';
protected static $dbFields = array("id" , "name" , "password" , "label");
protected $id;
/**
* #type: SQL.varchar(64)
* Name of the user, should not contain anything other than alpha and whitespace
*/
protected $name; //TODO : TEST what happens while saving if some variable is not set
/**
* #type: SQL.varchar(64)
* Encrypted user password, Real Escaping is done after the encryption
*/
protected $password;
protected $label;
public function __construct(){
parent::__construct();
}
/**
* get functions
*/
public function getId(){
return $this->id;
}
public function getLabel(){
return $this->label;
}
/**
* Sets all the properties of object.
* Must call this function before calling save on this object, if not initialized by find* functions
*/
public function initialize($name=null , $password=null , $label= null){
if(Validator::isValidEmail($name)){
$this->name = $name;
}else {
throw new InvalidUserData("Username is not valid");
}
if(Validator::isValidPassword($password)){
$this->password = Texter::encryptPassword($password);
}else {
throw new InvalidUserData("Password is not valid");
}
$this->label = $label;
}
/**
* #Defination: Reset saved password
* */
public function setPassword($newPass) {
if(Validator::isValidPassword($newPass)){
$this->password = Texter::encryptPassword($newPass);
}else {
throw new InvalidUserData("Password is not valid");
}
return $this;
}
/**
* #Defination: Authenticate user by name and password
* #return: Object of this class if authenticated, null otherwise
*/
public static function authenticate($name = null , $password = null){
if(! Validator::isValidEmail($name) || ! Validator::isValidPassword($password))
return null;
$name = self::escapeValue($name);
/**TODO, find how right is next step ? */
$password = Texter::encryptPassword($password);
$password = self::escapeValue($password);
$sql = "SELECT * FROM ".static::$tableName;
$sql .= " WHERE name = '{$name}' AND ";
$sql .= "password = '{$password}' ";
$sql .= "LIMIT 1";
$resultSet = self::findBySQL($sql);
return !empty($resultSet) ? array_shift($resultSet) : null;
}
public static function findByUsername($name = null){
if(! Validator::isValidEmail($name)) return null;
$name = self::escapeValue($name);
$sql = "SELECT * FROM ".static::$tableName ." WHERE name='{$name}' LIMIT 1";
$resultSet = self::findBySQL($sql);
return !empty($resultSet) ? array_shift($resultSet) : null;
}
}
PS. I might need to upload other codes as well but I'm not sure what it is.
I assume it, config.php is your database file. If yes change the order of file to top and then try.
I've just started learning to do oop and I just wanted to put the most basic set of code together to make sure I'm understanding things correctly. I wanted to capture a form entry in the $_POST variable and pass it to an object to have it output something back to the browser. No SQL, no Security measures, just proof of understanding.
Here is the form:
<html>
<head>
<title>SignUp Form</title>
</head>
<body>
<?php
if(!empty($_POST['name'])) {
include_once "class.php";
} else {
?>
<form method="post" action="signup.php">
<label for="name">Enter name below:</label></br>
<input type="text" name="name" id="name"></br>
<input type="submit" value="Submit">
</form>
<?php
}
echo $name->processName($_POST['name']); ?>
</body>
</html>
And here is the class:
<?php
class Process {
public $entry;
function __construct($entry) {
$this->entry = $entry;
}
public function processName($entry) {
return "You entered " . $this->entry . ".";
}
}
$name = new Process($_POST['name']); ?>
This is working without error right now but it doesn't seem like I should have to enter the $_POST in the echo statement on the form page and in the object on the class page. Is this correct? Should I instead be collecting that in the $entry property. It's working, but I don't think the execution is correct. Thanks in advance!
Your right you don't need to enter the $_POST variable into that function, you could change it to this and it would work without entering the post:
public function processName() {
return "You entered " . $this->entry . ".";
}
Because right now processName function doesn't do anything with the class's public $entry variable, it just echoes out what you put in when you call the function.
What you likely want to do instead is:
Change public $entry; to protected $entry;
Then:
public function getEntry() {
return $this->entry;
}
Then in your html, after constructing the class, you can just put this to get the $entry variable:
echo $name->getEntry();
Coming from Symfony framework background. You could do something right this:
<?php
class Process
{
protected $post_var;
public function __construct($p)
{
$this->post_var = $p;
}
public function getData()
{
//checking if not post request
if(count($this->post_var) == 0) {
return false;
}
$result_arr = [];
//populating $result_arr with $_POST variables
foreach ($this->post_var as $key => $value) {
$result_arr[$key] = $value;
}
return $result_arr;
}
}
$process = new Process($_POST);
$data = $process->getdata();
if($data)
{
echo $data["name"];
}
?>
<form action="" method="post">
<input type="text" name="name"/>
<input type="submit" name="submit"/>
</form>
i bet there are scripts out there already about this, but I'm creating this project just for fun and to test my knowledge, now i just want the public's opinions, and if you guys find a way I could improve feel free to share as well to comment against it.
My question is simply how to create a good salt. after reading the manual, and a few book chapters this is what i came up with. Although i feel like my salt should be longer for security. what should I change?
Here is my user class. please check genSalt() function and guide me to figure out how to improve my results.
<?php
if(!defined('ACCESS_CORE')){
echo 'Permission Not Granted';
exit;
}
class user{
private $_email;
private $_pass;
private $_db;
private $_url;
function __construct(){
$this->_db = $this->db();
$this->_url = 'localhost'; //change this to ur url
if(isset($_POST['user_login'])){
$this->_email = $this->clean($_POST['user_email']); //sanitize later
$this->_pass = $this->clean($_POST['user_password']);
}
}
protected function db(){
$db = parse_ini_file('../contra.conf');
$this->_db = new mysqli($db['host'], $db['user'], $db['pass'], $db['name']);
if ($this->_db->connect_errno) {
trigger_error("Failed to connect to MySQL".$mysqli->connect_errno). $mysqli->connect_error;
}
}
protected function clean($string){
return mysql_real_escape_string($string); #TODO: add more options html etc
}
public function safeReferer(){
$ref = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''); //if there is a ref..
if(empty($ref) || strpos($ref, $this->_url)){
return true;
} else {
return false;
}
}
public function includeForm($message = ""){ #TODO: finish form view page
?>
<div id="logForm">
<h3>User Authentication Form</h3>
<?php echo ($message === "") ? '' : $message; ?>
<form id="loginForm" method="post" action="login.php">
<input type="text" name="user_email" />
<input type="password" name="user_password" />
<input type="submit" value="Login" name="user_login" />
<a href="/" >Forgot password?</a>
</form>
</div>
<?php ;
}
protected function genSalt($length) { #TODO: improve something is fishy
$prefix = '$2a$'.$length.'$'; //blowfish prefix
//base64 unique random alphanumeric
$uniqRand = base64_encode(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM));
$modified_string = str_replace('+', '.', $uniqRand);
$salt = substr($modified_string, 0, $length);
return $prefix.$salt.'$';
}
protected function correctPass($password, $salt){ #TODO: change to prepared statement. best method?
$sql = "SELECT pass, s FROM users WHERE email = '$this->_email'";
if($result = $this->_db->query($sql)){
while ($row = $result->fetch_object()) {
if(cript($row['pass'], $row['s']) === $row['s']){
return true;
} else {
return false;
}
}
}
}
public function login(){
if($this->correctPass($this->_email, $this->_pass)){
echo 'create session, session cookie, start timeout, and redirect'; #TODO: copy login, finish page on form view
} else {
$message = '<h5>Please try again</h5>';
$message .= '<p>It looks like you have either entered a wrong user name or password.';
$this->includeForm($message);
}
}
// test function, similar function in register class
public function createPass($pass){
$salt = $this->genSalt(10);
$hash = crypt($pass, $salt);
echo $salt. '--';
echo 'hashed pass : '. $hash;
echo '<br> entered pass : '.$pass.'<br>';
if(crypt($pass, $hash) == $hash ){
echo 'true';
} else {
echo 'false';
}
}
}
?>
test function results...
$2a$10$WlUvRqsgZl$--
hashed pass : $2a$10$WlUvRqsgZl$$$$$$$$$$$. tRNdwECDQXhN07g4mIp82xxFCTUev3m
entered pass : mypassword
true
Why not consider the password_hash function? It also hashes but generates a random salt every time and uses blowfish by default. It requires PHP 5.5 or later, however.
Im trying to use ajax to submit a form and return type either Business or Admin but I'm getting:
JSON.parse: unexpected end of data
result= JSON.parse(r);
<input type="text" id="signinemail" placeholder="Email" name="signinemail">
<input type="password" id="signinpassword" placeholder="Password"
name="signinpassword">
<script>
$(function() {
$("#signinsubmit").click(function() {
var username = $("#signinemail").val();
$.post("signin.php",
{
signinusername: username, signinpassword: $("#signinpassword").val()
} )
.done( function(r)
{
result= JSON.parse(r);
if(result["user_type"]=="Business")
{
window.location="profile.php";
}
else if(result["user_type"]=="Admin")
{
window.location="requestpage.php";
}
});
});
});
</script>
This is the class that trying to login in with. It firsts takes the post gives it to the authenticate function then returns the result of the connection to the log in function that encodes it
<?php
/**
* Logs the User into Website
*/
class Login
{
private $connection;
private $result_array = array();
private $user_type;
private $id;
public $username;
private $password;
public $loggedIn;
function __construct()
{
$this->username = $_POST['signinemail'];
$this->password = $_POST['signinpassword'];
$this->connection = new mysqli('WolfeboroC.db.10688096.hostedresource.com', 'WolfeboroC', 'Brewster#1', 'WolfeboroC');
$this->authenticate();
$this->logIn($this->authenticate);
}
private function authenticate()
{
$query = "SELECT recid, Admin FROM users
WHERE User = '".$this->$username."'
AND password='".$this->$password."'
AND (verified='y' OR admin = 'y')
LIMIT 1";
$stmt = mysqli_master_query($this->connection, $query);
$this->result_array = mysqli_fetch_array($stmt);
return !empty($this->result_array);
}
private function logIn()
{
if($result_array->num_rows > 0)
{
if($result_array['Admin']=='y')
{
$this->user_type = "Admin";
$this->admin($this->result_array);
$this->loggedIn = true;
}
else
{
$this->user_type = "Business";
$this->business($this->result_array);
$this->loggedIn = true;
}
echo json_encode($this->user_type['user_type']);
}
}
}
?>
echo json_encode($this->user_type['user_type']); is not correct. Your user_type is not an array so don't try to access it like this. You either do a echo $this->user_type and use the result as a string in javascript OR put the value in an array and then json_encode it like this:
echo json_encode(array('user_type' => $this->user_type));
Try using to get json response as,
result.user_type
instead of
result["user_type"]
In login() function: json synatx should be
echo json_encode(array('user_type' => $this->user_type));
instead of,
echo json_encode($this->user_type['user_type']);
ive got the following ajax call, which appears to be working(as in the form submits, the loader shows etc)
<?PHP
session_start();
include('includes/class.login.php');
$login = new Login();
$token = $_SESSION['token'] = md5(uniqid(mt_rand(), true));
if ($_POST['ajax']) {
exit($login->getStatus());
}
?>
<style>
#message { display: none; cursor: pointer; }
.loader { display: none; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(e) {
$(this).fadeOut(300);
$('.loader').delay(300).fadeIn(100);
$.post("<?=$_SERVER['PHP_SELF'];?>", { username: $('#username').val(), password: $('#password').val(), ajax: true }).done(function(data) {
if (data.logged_in == 1) {
// Redirect with javascript
$('.loader').delay(2000).fadeOut(100);
$('#message').html('<p>Success! We\'ll redirect you in a minute...</p>'+data.logged_in).delay(2200).fadeIn(200);
} else {
// Inject errors to html
// data.errors
$('.loader').delay(2000).fadeOut(100);
$('#message').html('<p>Failed... Click to try again!'+data.errors+data.logged_in).delay(2200).fadeIn(200);
$('#message').on('click', function(){
$(this).fadeOut(200);
$('#loginForm').delay(350).fadeIn(200);
});
}
});
return false;
});
});
</script>
<form id="loginForm" method="POST" action="">
<table>
<tr><td>Username:</td><td><input type="text" name="username" id="username"/></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" id="password"/></td></tr>
</table>
<input type="hidden" name="token" value="<?=$token;?>"/>
<input type="submit" name="login" value="Log In"/>
</form>
<div class="loader">
<img src="loader.gif"/>
</div>
<div id="message"></div>
You'll see in my message outputs i've tried appending data.errors and data.logged_in to find out what values they are holding, however they both just come back as undefined.
The JSON code in my php class is this:
public function getStatus()
{
return json_encode(
array(
'logged_in' => $this->isLoggedIn(),
'errors' => $this->showErrors()
)
);
}
Entire PHP class:
<?PHP
class Login
{
private $_id;
private $_username;
private $_password;
private $_passmd5;
private $_errors;
private $_access;
private $_login;
private $_token;
public function __construct()
{
$this->_errors = array();
$this->_login = isset($_POST['login']) ? 1 : 0;
$this->_access = 0;
$this->_token = $_POST['token'];
$this->_id = 0;
$this->_username = ($this->_login) ? $this->filter($_POST['username']) : $_SESSION['username'];
$this->_password = ($this->_login) ? $this->filter($_POST['password']) : '';
$this->_passmd5 = ($this->_login) ? md5($this->_password) : $_SESSION['password'];
}
public function isLoggedIn()
{
($this->_login) ? $this->verifyPost() : $this->verifySession();
return $this->_access;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifyPost()
{
try
{
if(!$this->isTokenValid())
throw new Exception('Invalid form submission');
if(!$this->isDataValid())
throw new Exception('Invalid form data entered');
if(!$this->verifyDatabase())
throw new Exception('Invalid username/password combination');
$this->_access = 1;
$this->registerSession();
}
catch(Exception $e)
{
$this->_errors[] = $e->getMessage();
}
}
public function verifySession()
{
if($this->sessionExist() && $this->verifyDatabase())
$this->_access = 1;
}
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT user_id FROM users WHERE user_username = '{$this->_username}' AND user_password = '{$this->_passmd5}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
public function isDataValid()
{
return (preg_match('/^[a-zA-Z0-9]/', $this->_username) && preg_match('/^[a-zA-Z0-9]/', $this->_password)) ? 1 : 0;
}
public function isTokenValid()
{
return (!isset($_SESSION['token']) || $this->_token != $_SESSION['token']) ? 0 : 1;
}
public function registerSession()
{
$_SESSION['id'] = $this->_id;
$_SESSION['username'] = $this->_username;
$_SESSION['password'] = $this->_passmd5;
}
public function sessionExist()
{
return (isset($_SESSION['username']) && isset($_SESSION['password'])) ? 1 : 0;
}
public function showErrors()
{
echo "<h3>Errors</h3>";
foreach($this->_errors as $key=>$value)
echo $value."<br>";
}
public function getStatus()
{
return json_encode(
array(
'logged_in' => $this->isLoggedIn(),
'errors' => $this->showErrors()
)
);
}
}
?>
isLoggedIn should be displaying either a 0 or 1 and showErrors shows an array of errors, but i'm getting nothing :(
I don't see where you are actually outputting your json array. When you output the JSON try putting the following line before it or use your framework to basically make sure you're outputting JSON headers.
if ($_POST['ajax']) {
header('Content-Type: application/json');
echo $login->getStatus();
exit();
}
Try making a non-AJAX form in a static file and submitting it to your PHP script. Do you get the JSON data back that you expect?
Another way to see the data is to use the network tab in your browser's developer tools (I'm used to Chrome, but other browsers have similar tools). This will tell you if the fault is in the Javascript on the client or the PHP on the server.