Sessions in AngularJS and PHP application - javascript

I have an AngularJS application that I am updating to use PHP 7. Currently I have a custom session handler setup for sessions:
Custom Session Handler (session.php)
function sess_open( $path, $name ) {
return true;
}
function sess_close( ) {
$sessionId = session_id();
return true;
}
function sess_read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
return $data;
}
function sess_write( $id, $data ) {
$db = dbConn::getConnection();
$tstData = sess_read( $id );
if (!is_null($tstData)) {
// if it does then do an update
$stmt = "UPDATE session SET session_data =" . $db->quote($data) . " WHERE session_id=" . $db->quote($id);
$db->query($stmt);
}
else {
// else do an insert
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ")";
$db->query($stmt);
}
return true;
}
function sess_destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
return $db->query($stmt);
}
function sess_gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
return $db->query($stmt);
}
session_name('PROJECT_CUPSAW_WEB_APP');
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
ob_flush();
In my app.js I have a continuous check to see if the user is authenticated and can access the application.
App.js
/*
* Continuous check for authenticated permission to access application and route
*/
app.run(function($rootScope, $state, authenticationService, ngToast) {
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
authenticationService.isAuthenticated()
.success(function () {
if(toState.permissions) {
ngToast.dismiss();
event.preventDefault();
$state.go("logout"); // NEEDS TO CHANGE - Unauthorized access view
return;
}
})
.error(function () {
ngToast.dismiss();
event.preventDefault();
localStorage.clear();
$state.go("authentication"); // User is not authenticated; return to login view
return;
});
ngToast.dismiss();
});
});
In the code above, isAuthenticated runs isUserAuthorized.php
isAuthenticated
/*
* Check if user is authenticated; set role/permissions
*/
this.isAuthenticated = function() {
return $http.post(baseUrl + '/isUserAuthorized.php');
};
isUserAuthorized.php
<?php
require_once 'session.php';
// Check to ensure user is authenticated to initiate request
if (array_key_exists('authenticated', $_SESSION) && $_SESSION['authenticated']) {
return http_response_code(200);
} else {
// Clear out all cookies and destroy session
if( array_key_exists('HTTP_COOKIE', $_SERVER)){
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
session_destroy();
return http_response_code(401);
}
The session should be started when session.php is required. It appears that this is not happening though. Upon accessing the application, the login page is displayed, but isUserAuthorized.php is throwing a warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
When I select the Login button, login.php is called, but the user gets brought right into the application, despite incorrect credentials.
login.php
<?php
require_once '../database.php';
require_once 'session.php';
require_once 'ldap.php';
$_SESSION['authenticated'] = false;
//$conn = connect_db();
try {
$data = json_decode(file_get_contents('php://input'));
$username = strtolower($data->username);
$password = $data->password;
// Check domain credentials; return user token if verified
if(ldap_authenticate($username, $password)) {
$_SESSION['authenticated'] = true;
}
else {
echo('Invalid username and/or password!');
return http_response_code(400);
}
}
catch(PDOException $e) {
return http_response_code(400);
}
I'm not entirely sure what's causing this odd behavior, and why the session isn't being created. Do I need to explicitly call the sess_write function?
Update
I discovered that removing the require_once 'session.php' from login.php causes the proper behavior. The user is able to login when they provide valid credentials. However, the session data is still never being written to the database. Any idea why?

The issues came down to my session handler. As of PHP 7, the sess_read function must return a string. This was causing the warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
I fixed this by returning '' when $data was null.
This caused issues with my sess_write function knowing when to insert and when to update. I fixed this by changing the SQL.
Ultimately I ended up making the session handler a class, as shown in the final result:
<?php
require_once ('../database.php');
class CustomSessionHandler implements SessionHandlerInterface{
public function open( $path, $name ) {
return true;
}
public function close( ) {
return true;
}
public function read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
if(!$data){
return '';
}
return $data;
}
public function write( $id, $data ) {
$db = dbConn::getConnection();
//Works with Postgres >= 9.5
//$stmt = "INSERT INTO session (session_id, session_data) VALUES (" . $db->quote($id) . ", " . $db->quote($data) . ") ON CONFLICT (session_id) DO UPDATE SET session_data=" . $db->quote($data) . ";";
//Works with Postgres < 9.5
$stmt = "UPDATE session SET session_data=" . $db->quote($data) . " WHERE session_id=" . $db->quote($id) . ";";
$db->query($stmt);
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ");";
$db->query($stmt);
return true;
}
public function destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
$data = $db->query($stmt);
return true;
}
public function gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
$data = $db->query($stmt);
return true;
}
}
session_name('PROJECT_CUPSAW_WEB_APP');
$handler = new CustomSessionHandler();
session_set_save_handler($handler, false);
session_start();
ob_flush();

Related

make a deactivate account with jquery, ajax and php prob

I am adding a deactivate feature on a website i am working on, so I added a form with a textarea to tell the reason why the user is deactivating his account and a button that become enabled when the textarea is filled out so I sent the call via jquery ajax to a php script which will update the users_table in the database to 1 for deactivated then must log the user out and redirect them to the index page of the website. So everything works fine except the log out it is not happening and no redirect. I need help with that please
here is my php script :
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
$user_id = (int)$_SESSION["user_id"];
if(isset($_POST['deactivate_reason'])) {
$deactivate_reason = mysql_prep($_POST['deactivate_reason']);
// INSERT into table
$query1 = "INSERT INTO deactivate_reason_table ( ";
$query1 .= "user_id, reason";
$query1 .= ") VALUES (";
$query1 .= " $user_id, '$deactivate_reason'";
$query1 .= ")";
$result1 = mysqli_query($connection, $query1);
$confirm_query1 = confirm_query($result1);
// if query1 is successful and replies deleted then we make the second query to delete the board comments
if ($confirm_query1 == 0) {
echo "error";
exit();
} else {
// UPDATE table
$query2 = "UPDATE users_table ";
$query2 .= "SET deactivated = 1";
$query2 .= "WHERE user_id = $user_id";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if ($confirm_query2 == 0) {
echo "error";
exit();
} else {
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
// redirect_to() is a custom function in the functions.php that redirects
redirect_to("../index.php");
}
}
}
and here is my jquery ajax script :
$(document).on("click", "#deactivate_button", function(e){
e.preventDefault();
var text = $("#deactivate_reason_textarea").val();
var url = "widgets/deactivate.php";
$.ajax({
url: url,
method: "POST",
data: {
deactivate_reason: text
},
beforeSend: function() {
CustomSending("Processing...");
},
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
}
});
});
To redirect the user for a another page in PHP you can use something like header('Location: ...') (manual), but you are calling the script in ajax, then you need to put the redirect in this, not in the called PHP script.
To redirect in JavaScript you can use window.location (tutorial).
window.location = "my/another/script.php";
In your case, you need to put it in the success of ajax.
$.ajax({
... # your occulted script
success: function(data){
$("#deactivate_reason_textarea").val("");
$("#dialogoverlay").fadeOut("Slow");
$("#sending_box").fadeOut("Slow");
$("body").css("overflow", "auto");
window.location = "another/script.php";
// or you can put it in a timeout to show a message for the user or other thing
// setTimeout(function() {
// window.location = "another/script.php";
// }, 10000);
}
});
ok guys thanks a lot for your help, I managed to solve this with your help
after i added widow.location = "insert.php" like tadeubarbosa suggested then i went to my index.php page and added these lines :
if (logged_in()) {
$email = $user_data['email'];
$id = $user_data['user_id'];
$edited = account_edited($email);
if ($edited == 0){
redirect_to("editprofile.php?id=$id");
}
$is_deactivated = is_deactivated($_SESSION['user_id']);
if ($is_deactivated == 1) {
$query = "UPDATE users_table SET online = 0 WHERE user_id = $id";
$result = mysqli_query($connection, $query);
if (isset($_COOKIE['username'])) {
// setcookie($name, $value, $expiration_time)
setcookie("username", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
if (isset($_COOKIE['user_id'])) {
setcookie("user_id", '', time() - 42000, '/', $_SERVER['SERVER_NAME'] );
}
session_destroy();
redirect_to("index.php");
}
}
then went to the login.php script and added a query to update deactivated = 0 if the user logs in so the account reactivates

Validate login form with JS/PHP

I want to be able to either send a user to a restricted area or return some text that says Email and or password do not exist or something similar. I'm having trouble getting this to work as whether or not the email and password are correct NOTHING happens. I'm sending the form to the index page where the script to run this sits. Not sure why I'm not redirecting or getting any kind of errors.
The restricted page checks if a $_SESSION variable isset(), if not then send them back home.
JS
loginBtn.addEventListener('click', e => {
e.preventDefault();
ajaxRequests.login(`login_email=${ loginEmail.value }&login_password=${ loginPassword.value }`);
});
ajaxRequests.login()
login(formData) {
return new Promise((resolve, reject) => {
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.send(formData);
this.xhr.onload = () => {
if (this.xhr.status == 200) {
resolve();
} else {
reject(this.xhr.statusText);
}
};
this.xhr.onerror = () => {
reject(this.xhr.statusText);
};
});
}
this is the script that is supposed to run when form is sent
if (isset($_POST['login_email']) && isset($_POST['login_password'])) {
$email = htmlentities($_POST['login_email'], ENT_QUOTES, 'ISO-8859-15');
$password = htmlentities($_POST['login_password'], ENT_QUOTES, 'ISO-8859-15');
$login = new Login($email, $password);
unset($login);
}
check for valid $_SESSION vars
session_start();
if (!isset($_SESSION['id']) || !isset($_SESSION['name']) || !isset($_SESSION['email'])) {
header('Location: index.php');
}
login query (just incase it is needed)
class Login extends Connection {
public function __construct($email, $password) {
$this->connect();
$sql = "SELECT `id`, `name`, `email`, `password` FROM `users` WHERE `email`=:email";
$query = $this->connect()->prepare($sql);
$result = $query->execute(
[
':email' => htmlentities($email, ENT_QUOTES, 'ISO-8859-15'),
]
);
// check if EMAIL exists
if ($result) {
$row = $query->fetch(PDO::FETCH_OBJ);
$id = htmlentities($row->id, ENT_QUOTES, 'ISO-8859-15');
$name = htmlentities($row->name, ENT_QUOTES, 'ISO-8859-15');
$email = htmlentities($row->email, ENT_QUOTES, 'ISO-8859-15');
$hashed_password = htmlentities($row->password, ENT_QUOTES, 'ISO-8859-15');
// check if user input PASSWORD matches the unhashed PASSWORD in the database
if (password_verify($password, $hashed_password)) {
$_SESSION['id'] = htmlentities($id, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['name'] = htmlentities($name, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['email'] = htmlentities($email, ENT_QUOTES, 'ISO-8859-15');
header('Location: blog_roll.php');
} else {
header('Location: index.php');
}
} else {
echo 'THAT EMAIL ADDRESS DOES NOT EXIST';
}
}
}
You have to set the content type for your ajax request
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.xhr.send(formData);

How to login with session using Angular?

login.js
$http({
url: 'http://ipadress/login.php',
method: 'POST',
data: {
'var_id': $scope.form.txt_id,
'var_pass': $scope.form.txt_pass
}
}//http
login.php
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
mysql_connect("localhost","root","password");
mysql_select_db("db");
$data = file_get_contents("php://input");
$dataJsonDecode = json_decode($data);
$var_id = $dataJsonDecode->var_id;
$var_pass = $dataJsonDecode->var_pass;
$sql = "SELECT * FROM user WHERE user_login = '".($id)."' and user_pass = '".md5($pass)."'";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
$resource = mysql_query($sql);
$count_row = mysql_num_rows($resource);
if (!$result) {
$results = '{"results":"not match"}';
} else {
$_SESSION["users_login"] = $result["users_login"];
session_write_close();
if($count_row > 0){
$results = '{"results":"match"}';
} else {
$results = '{"results":"Error"}';
}
}
echo $results;
?>
$http.get('http://ipaddress/data_user.php')
.then(function (response) {
console.log(response.data.results);
$scope.myData = response.data.results;
}, function (error) {
console.log(error);
});
user_data.php
<?php
session_start();
if($_SESSION['users_login'] == ""){
$results = '{"results":"Please Login"}';
echo $results;
}
else{
mysql_connect("localhost","root","password");
mysql_select_db("db");
mysql_query( "SET NAMES UTF8" );
$sql = "SELECT * FROM users WHERE users_login = '".$_SESSION["users_login"]."' ";
$query = mysql_query($sql);
$count_row = mysql_num_rows($query);
if($count_row > 0){
while($result = mysql_fetch_array($query)){
$rows[] = $result;
}
$data = json_encode($rows);
$totaldata = sizeof($rows);
$results = '{"results": '.$data.'}';
}
echo $results;
}
?>
I have problem with login. My $results = please login.
First check what $result["users_login"] contains..
You are getting the please login because you don't have the session data.
I am not sure about your approach, but don't mix php session and Ionic, You can create a kind of API to check user credentials from your ionic App, or else handle it in the ionic app.
Session normally used in websites to pass data through out the page, not for API calls. Think of scenario 10 users access your app simultaneously, How you going to use the Session to verify them?
My advise is, instead of using PHP sessions, you can handle your sessions inside your app using the session storage
Read this. There are plenty of plugin available. OR you can create your as shown here
Good Luck!!

Call to undefined method mysqli_stmt::get_result() on line 43 [duplicate]

This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 6 years ago.
I have a small problem. When I try to login on a script I worked on I can not login. I hope you guys can help me out. For some reason I get this MySQL error:
Call to undefined method mysqli_stmt::get_result() in
home/[username]/public_html/inc/session.php on line 43
The code for session.php:
<?php
class Session {
private $self_file = 'session.php';
private $mysqli = false;
public function __construct($m) { $this->mysqli = $m; }
public function isLogged() {
if(!isset($_SESSION['invento_logged']) || !is_array($_SESSION['invento_logged']))
return false;
if(!isset($_SESSION['invento_logged']['u']) || !isset($_SESSION['invento_logged']['p']))
return false;
$u = $_SESSION['invento_logged']['u'];
$p = $_SESSION['invento_logged']['p'];
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'isLogged()');
$this->execute($prepared, 'isLogged()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c == 1)
return true;
return false;
}
public function refresh_password($pass) {
$_SESSION['invento_logged']['p'] = md5($pass);
return true;
}
public function login($u, $p) {
$p = md5($p);
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'login()');
$this->execute($prepared, 'login()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c != 1)
return false;
$_SESSION['invento_logged']['u'] = $u;
$_SESSION['invento_logged']['p'] = $p;
return true;
}
public function logout() {
if(isset($_SESSION['invento_logged']))
$_SESSION['invento_logged'] = false;
unset($_SESSION);
session_destroy();
return true;
}
public function get_user_id() {
$username = $_SESSION['invento_logged']['u'];
$prepared = $this->prepare("SELECT id FROM invento_users WHERE username=?", 'get_user_id()');
$this->bind_param($prepared->bind_param('s', $username), 'get_user_id()');
$this->execute($prepared, 'get_user_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->id;
}
public function get_user_name_by_id($id) {
$prepared = $this->prepare("SELECT username FROM invento_users WHERE id=?", 'get_user_name_by_id()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_name_by_id()');
$this->execute($prepared, 'get_user_name_by_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->username;
}
public function get_user_role() {
$id = $this->get_user_id();
$prepared = $this->prepare("SELECT role FROM invento_users WHERE id=?", 'get_user_role()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_role()');
$this->execute($prepared, 'get_user_role()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->role;
}
/***
* Private functions
*
***/
private function prepare($query, $func) {
$prepared = $this->mysqli->prepare($query);
if(!$prepared)
die("Couldn't prepare query. inc/{$this->self_file} - $func");
return $prepared;
}
private function bind_param($param, $func) {
if(!$param)
die("Couldn't bind parameters. inc/{$this->self_file} - $func");
return $param;
}
private function execute($prepared, $func) {
$exec = $prepared->execute();
if(!$exec)
die("Couldn't execute query. inc/{$this->self_file} - $func");
return $exec;
}
private function query($query, $func) {
$q = $this->mysqli->query($query);
if(!$q)
die("Couldn't run query. inc/{$this->self_file} - $func");
return $q;
}
public function __destruct() {
if(is_resource($this->mysqli) && get_resource_type($this->mysqli) == 'mysql link')
$this->mysqli->close();
}
}
$_session = new Session($mysqli);
and the code for config.php:
<?php
session_start();
/************ You can edit details starting from here ************/
$dbhost = '(I've filled this in'; // Write your MySQL host here.
$dbuser = 'I've filled this in'; // Write your MySQL User here.
$dbpass = 'I've filled this in'; // Write your MySQL Password here.
$dbname = 'I've filled this in'; // Write the MySQL Database where you want to install
/************ DON'T EDIT NOTHING BELOW ************/
if(!isset($noredir) && $dbhost == 'localhost' && $dbuser == 'MYSQL USERNAME' && $dbpass == 'MYSQL PASSWORD')
header('Location:install.php');
if(!isset($noredir)) {
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno)
die('<h2>Something went wrong while trying to connect to your MySQL Database. Error No. ' . $mysql->connect_errno.'<h2>');
// Check existance of random table to test installed system
$tables = array('users','categories','items','logs','settings');
$rn = rand(0,4);
$res = $mysqli->query("SHOW TABLES LIKE '%invento_{$tables[$rn]}%'");
if($res->num_rows == 0)
header('Location:install.php');
}
I hope you guys can help me out.
Thanks in advance,
Bram
I think it's because of the version of PHP that you are using.
As mentioned in php documentation mysqli_stmt::get_result, this method is supported since PHP 5.3.0.
And it is stated in the user notes section that:
This method requires the mysqlnd driver. Othervise you will get this error: Call to undefined method mysqli_stmt::get_result()
Instead of this function, try using bind_result function.
Helpful link
http://php.net/manual/en/mysqli-stmt.get-result.php

Jquery $.post returns object

I am attempting to have the user enter their un/pw, click a button, have a javascript function take the un/pw entered, send it to a php script which will return a 1 or 0 based on whether the un/pw was valid.
In the javascript page I have:
function handleLogin() {
var username = document.getElementById('un').value;
var password = document.getElementById('pw').value;
var valid = $.post("getLogin.php", {"un": username, "pw": password}, "json");
alert(valid);
}
In the php file I have:
$username = $_POST['un'];
$password = $_['pw'];
$valid = 0;
# This section will open a connection to the existing backup server and get the last ith_rid used.
# It will then store that ith_rid to be used later and then close the database connection
$mysqlconn = new mysqli('localhost','username','password','database');
if ($mysqlconn->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqlconn->connect_errno . ") " . $mysqlconn->connect_error;
}
###################################################
## Get username and password
##################################################
$res = $mysqlconn->query("SELECT username, password FROM table WHERE username = '" .$username . "'");
if (!$res) { ##If there is an error running query, display it to the screen.
echo "Error: $mysqlconn->error \n";
}
while($row = $res->fetch_assoc()) {
$un = trim($row["username"]);
$pw = trim($row["password"]);
}
if ($un == $username && $pw == $password){
$valid = 1;
}
echo json_encode($valid);
The php does return something, but it is in an object. Not sure how to access the variable from the javascript in order to determine if it is 1 or 0.
Edit:
So I changed things up a bit and it is working correctly now.
carrierchange.js
jQuery(document).ready(function () {
$("#content").append("<form name='loginForm' autocomplete='off'>");
$("#content").append("<table align=center>");
$("#content").append("<tr><td colspan=2 bgcolor=#87C9FF><center><h2>Login</h2></center></td></tr>");
$("#content").append("<tr><td><label for='un'>Username:</label></td><td><input id='un' name='un'></td></tr>");
$("#content").append("<tr><td><label for='pw'>Password:</label></td><td><input id='pw' name='pw' type='password'></td></tr>");
$("#content").append("<tr><td colspan=2><center><input type='submit' class='btn' value='Login' onClick='handleLogin()'></center></td></tr>");
$("#content").append("</table>");
$("#content").append("</form>");
document.getElementById('un').focus().focus();
});
function handleLogin() {
var username = document.getElementById('un').value;
var password = document.getElementById('pw').value;
var valid;
$.get("getLogin.php", {un: username, pw: password}, "json", function(data) {
console.log(data);
});
}
getLogin.php
<?php
$username = $_GET['un'];
$password = $_GET['pw'];
$valid = 0;
# This section will open a connection to the existing backup server and get the last ith_rid used.
# It will then store that ith_rid to be used later and then close the database connection
$mysqlconn = new mysqli('localhost','username','password','datebase');
if ($mysqlconn->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqlconn->connect_errno . ") " . $mysqlconn->connect_error;
}
###################################################
## Get username and password
##################################################
$res = $mysqlconn->query("SELECT username, password FROM cc_user WHERE username = '" .$username . "'");
if (!$res) { ##If there is an error running query, display it to the screen.
echo "Error: $mysqlconn->error \n";
}
while($row = $res->fetch_assoc()) {
$dbusername = trim($row["username"]);
$dbpassword = trim($row["password"]);
}
if ($dbusername == $username){
$valid = 1;
}
echo json_encode($valid);
?>
Since $.post is an asynchronous request, you should handle the received data in the callback function:
$.post("getLogin.php", {"un": username, "pw": password}, "json", function(data) {
console.log(data); //received data
});

Categories

Resources