MySQL not working on localhost - php

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.

Related

Send Form data variables into flutter app

I have a php mvc website that contain controller - model - view
How I can call a function in flutter.
fo example the login form of the website has:
controller function:
function checkuser()
{
$form= $_POST;
$error=$this->model->checkUser($form);
Model::sessionInit();
$userId=Model::sessionGet('userId');
if ($userId==false )
{
// header('location:'.URL.'login');
echo '<script>console.log("invalid username or password")</script>';
}
else
{
// header('location:'.URL.'userpanel');
echo '<script>console.log("successfull... you are in.")</script>';
}
if ($error !='')
{
echo '<script>console.log("there is some error")</script>';
// $data=['error'=>$error];
// $this->view('login/index',$data);
}
}
and the model is:
function checkUser($form)
{
#$email=$form['username'];
#$password=$form['password'];
#$remember=$form['remember'];
$error='';
$sql= "select * from tbl_users WHERE email=? and password=?";
$params=[$email,$password];
$result=$this->doSelect($sql,$params,1);
if (sizeof($result)>0 and !empty($email) and !empty($password))
{
Model::sessionInit();
Model::sessionSet('userId',$result['id']);
if ($remember=='on')
{
$expiry = time() + (86400 * 7);
setcookie('userIdc',$result['id'],$expiry,'/');
}
}
else {
$error='not found user.';
}
return $error;
}
the link of the controller will be /login/checkuser
I try to send request from flutter with http package but can not give a good result.
please help me about the structure of the code in flutter and how to send the data username and password to server and give feedback from there.
thanks so much.
best regards
try something like below
import 'package:http/http.dart' as http;
import 'dart:convert';
userLogin() async {
Map<String, String?> userData = {
'username': 'username',
'password': 'password'
};
http.Response response = await http.post(
Uri.parse('yourUrl'),
headers: {'youHeader'},
body: json.encode(userData),
);
String jsonStr = (response.body);
try {
final mapData = jsonDecode(jsonStr);
if (mapData is Map) {
// var loginSuccess = await(AfterLogin.updatesAfterLogin(mapData)); //do other stuffs
} else {
return false;
}
} catch (e, trace) {
debugPrint("error $e, ${trace.toString()}");
return false;
}
}

Navigation to next page : if statement don't work with response message in Xamarin

I have login page in Xamarin forms app, the page send request to PHP file and check the username and password ,then response a message ,C# Code :
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using static JiyanUQuran.Models.appuser;
namespace JiyanUQuran.views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
}
private void Signin_Clicked(object sender, EventArgs e)
{
string user = username.Text;
string pass = password.Text;
Navigation.PushModalAsync(new MonthPage());
string response = SendRequest("xxx/api/xxx.php?username=" + user + "&password=" + pass);
if (response == "Welcome")
{
Navigation.PushModalAsync(new MonthPage());
}
else
{
message.Text = response;
}
}
private string SendRequest(string url)
{
try
{
using (WebClient client = new WebClient())
{
return client.DownloadString(new Uri(url));
}
}
catch (WebException)
{
return null;
}
}
}
}
the PHP page is like this :
<?php
$message = "Empty Field not Allowed";
include_once 'DbConnect.php';
$username = $_GET['username'];
$password = md5($_GET['password']);
$testuser = "SELECT * FROM users Where username = '$username'";
$testresult=mysqli_query($connection,$testuser);
$counttest = mysqli_num_rows($testresult);
if ($counttest == 0){
$rigister=mysqli_query($connection,"INSERT INTO users Values ('','$username','$password')");
}
else {
$user = "SELECT * FROM users Where username = '$username' and password = '$password'";
$result=mysqli_query($connection,$user);
$count = mysqli_num_rows($result);
if ($count == 0){
$message= "username or password is wrong";
}
else{
$message ="Welcome";
}
}
echo $message;
?>
When the username or password wrong I received the message correctly but i don't wan to navigate to other page ,but in all response it is navigate to next page ,how can i solve this?
There are two Navigation.PushModalAsync methods in your Signin_Clicked function, the first one will be called directly, the second one will be called when the response equals to "Welcome".
So your problem is caused by the first Navigation.PushModalAsync, remove it and choose whether to navigate to MonthPage by the response.
private void Signin_Clicked(object sender, EventArgs e)
{
string user = username.Text;
string pass = password.Text;
//remove this line
//Navigation.PushModalAsync(new MonthPage());
string response = SendRequest("xxx/api/xxx.php?username=" + user + "&password=" + pass);
if (response == "Welcome")
{
Navigation.PushModalAsync(new MonthPage());
}
else
{
message.Text = response;
}
}

Im trying to create a login class but my ajax json parsing isn't getting a correct response

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']);

OOP and AJAX form submission issues

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.

'Undefined' when using OOP and AJAX login

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.

Categories