Get and set session using PHP and angular.js - javascript

I need one help session store using PHP and Angular.js . i have one login app.When user will logged in successfully the session will store and when user will redirect to next page the session data will be fetched.I am explaining my code below.
login.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user_name=$request->user_name;
$user_pass=$request->user_pass;
$connect = mysql_connect("localhost", "root", "*****");
mysql_select_db('go_fasto', $connect);
$selquery = "SELECT * FROM db_Admin_Master WHERE user_name='".$user_name."' and password='".$user_pass."'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0){
$result=mysql_fetch_array($selres);
$_SESSION["user_name"]=
$_SESSION["user_type"]=
$_SESSION["email_id"]=
$result['msg'] = 'Login successfull...';
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = 'You entered wrong username/password';
}
echo json_encode($result);
?>
In this page i need to set up the session data(i.e-user_name,email_id,user_type).The user will redirect to the next page after successful login and the controller file of that redirected page is given below.
dashboardController.js:
var dashboard=angular.module('Channabasavashwara');
dashboard.controller('dashboardController',function($scope,$http){
$http({
method: 'GET',
url: 'php/Login/session.php',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
})
In this page the user will get the respective session data inside success function and if session data is not present some message will return to error call back function.Please help me.

I think you need to create one separate function for that.
For example
$selquery = "SELECT * FROM db_Admin_Master WHERE user_name='".$user_name."'
and password='".$user_pass."'";
$selres = mysql_query($selquery);
if(mysql_num_rows($selres ) > 0){
$result=mysql_fetch_array($selres);
getSession($result);
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg'] = 'You entered wrong username/password';
}
/*May be in separate function file.*/
function getSession($result){
if (! isset ( $_SESSION )) {
session_start ();
}
if( isset($result['user_id'])){ //or Whatever
// Declare your session and return variable
}
}
And call getSesson() function wherever you need to check session.

Related

Prevent Direct access to PHP file using AJAX

I want to prevent direct access to a certain PHP file called prevented.php
My logic is that I have a main file lets call it index.php and it generates a token and stores it in a $_SESSION variable. I also have a another file called def.php which is called using AJAX and it passes the token from the index.php to the def.php and if the $_SESSION['token'] is equal to the $_POST['token'] it defines a _DEFVAR and returns true otherwise it returns false. After I called the def.php and it returns true, I redirect to the prevented.php via javascript using location.href="prevented.php". In the top of the prevented.php file there is a code which checks if the _DEFVAR is defined or not. If not, its die with a message like invalid otherwise it displays the content of the prevented.php file. But somewhy I always get invalid message and I don't know why. Any idea how to reach the prevented.php without directly direct the page?
Here's my code:
index.php
<?php
$_SESSION["token"] = hash_hmac('sha256', "tokenString", "t2o0k0e0n3"); // Creates a hashed token
?>
<script>
$.ajax({
type: "POST",
url: "def.php",
data: {
token: '<?php echo $_SESSION["token"]; ?>'
},
cache: false,
success: function(data) {
console.log (data);
if (data) {
console.log (data + ' valid');
} else {
console.log (data + ' invalid');
}
location.href = "prevented.php";
},
error: function () {
console.log('error');
}
});
</script>
def.php
<?php
session_start();
if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {
echo false;
die('invalid in def');
} else {
define('_DEFVAR', 1);
echo true;
die ('valid in def');
}
?>
prevented.php
<?php
include "def.php";
if (defined('_DEFVAR')) {
die ('valid in prevented'); // instead of this I would show the content of the page
} else {
die ('invalid in prevented');
}
?>
Your code is unnecessarily overcomplicated. If your intent is merely to ensure that visitors to protected.php have first visited index.php then all you need to do is create a session flag in one and check for its existence in the other. There is no need for any AJAX or any form POSTs. The innate behavior of PHP sessions already gives you this functionality.
index.php:
<?php
session_start();
$_SESSION['flag'] = true;
?>
click here for the protected page
protected.php:
<?php
session_start();
if ($_SESSION['flag'] ?? false) {
echo "you have previously visited index.php";
} else {
echo "you have not previously visited index.php";
}
?>

Secure AJAX POST/GET jquery

So basically my question is simple.
Imagine situation when you a making a login or register form. With jquery.post i make ajax call
$.post( "pages/form_handle.php", name: $.(".username").val(), pass: $.(".pass").val() , function( data ) {
$( ".result" ).html( data );
});
it's simple call(i belive so)...
How to make it secure?
So if user look in my source code he or she know where i send my data in example pages/form_handle.php also he or she know what data i send to this page.
One of idea what i have simple send all ajax calls to one page ajax.php adding extra variables who will call right php function for ajax call...
But does it is the right way? Or maybe there is some better way to make it secure?
Stick to basics, and keep salting your passwords.
AJAX is not server side language, its a javascript plugin that does the same thing as forms, actions, etc... just in background as a new request.
Your ajax is not in danger, but your php files are, you can use jquery-validate.js to check on users input, but also you should make validation check in your ajax.php.
Here is a simple ajax login request:
function loginUser() {
var process = "loginUser";
var data = $("form").serializeArray();
data[1].value = data[1].value; // data to ajax.php page
data = JSON.stringify(data);
$("#loginButton").html('Login');
$.ajax({
type: "POST",
url: "ajax.php",
data: {"process": process, "data": data},
success: function(data) {
if (data.response.state == "success") {
// if ajax.php returns success, redirect to homepage or whatever
} else {
// if ajax.php returns failure, display error
}
},
error: function(jqXHR, textStatus, errorThrown, data) {
// error handling
},
dataType: "json"
});
}
And the simple ajax.php login:
<?php // ajax.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
if (isset($_SERVER['PHP_AUTH_USER']) &&
isset($_SERVER['PHP_AUTH_PW'])){
$un_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_USER']);
$pw_temp = mysql_entities_fix_string($_SERVER['PHP_AUTH_PW']);
$query = "SELECT * FROM users WHERE username='$un_temp'";
$result = mysql_query($query);
if (!$result) die("Database access failed: " . mysql_error());
elseif (mysql_num_rows($result)){
$row = mysql_fetch_row($result);
$salt1 = "qm&h*";
$salt2 = "pg!#";
$token = md5("$salt1$pw_temp$salt2");
if ($token == $row[3]) echo "$row[0] $row[1] :
Hi $row[0], you are now logged in as '$row[2]'";
else die("Invalid username/password combination");
} else die("Invalid username/password combination");
}else{
header('WWW-Authenticate: Basic realm="Restricted Section"');
header('HTTP/1.0 401 Unauthorized');
die ("Please enter your username and password");
}
function mysql_entities_fix_string($string){
return htmlentities(mysql_fix_string($string));
}
function mysql_fix_string($string){
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
?>

How can I attach the POST variable values to a new SESSION variable in AJAX and call it from other script?

I checked the accepted answer of this question it but didn't help
I'm trying to make an AJAX Post Request to sumbit my signup form, the ajax.php file will check the entered information, example passwords match or not, and then attach the $_POST variable to a $_SESSION variable so that I can call the submitted data from any other page later.
Ajax.php
...
if ($everythingValid) {
// add this user to db
$_SESSION["signup_details"] = $_POST;
echo "SUCCESS#".$core->signupPaymentUrl($package); // tried without this line but didn't work
exit(); // tried without this line but didn't work
} else {
foreach ($errors as $e) print "<br>".$e;
exit();
}
...
The jquery code that I'm using to call the file is the below:
var form = $('#signup');
$("#submit").click(function() {
$.ajax( {
type: "POST",
dataType: 'html',
crossDomain: true,
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
if ("SUCCESS" === $.trim(response.split('#')[0])) {
// user created, redirect to payment page
var paymentUrl = $.trim(response.split('#')[1]);
window.location.href = paymentUrl;
} else {
$("b#signupErr").hide();
$("b#signupErr").html(response);
$("b#signupErr").fadeIn();
}
}
} );
});
After submitting the form, I successfully get redirected to the payment Url, however, after accessing the page where I want to use my session, I cannot figure out how to retrieve my session although I'm pretty sure that I have included session_start in both of ajax.php and completeOrder.php and no blank spaces before the opening php tag.
here is the line that I included in both files :
if(!session_id()) session_start();
I tried to var_dump the $_SESSION variable on ajax.php and It looks okay. However when I var_dump the session variable on completeOrder.php it shows me NULL
Finally here is the completeOrder.php content
if(!session_id()) session_start();
require_once("core.php");
$core = new coreOptions();
$email = $_SESSION["signup_details"]["email"];
$password = $_SESSION["signup_details"]["password"];
$package = $_SESSION["signup_details"]["pkg"];
$options = $core->attachOptions($package);
if ($core->registerUser($email,$password,$options,$package))
$core->redirect("registrationCompleted.php");
in the completeOrder.php file remove if(!session_id()) session_start();
and then only add session_start(); and it will do the trick!
session_id() will return an empty string in ajax.php if there was no call to session_start() before. So the in ajax.php session_start() will never be called and the content of $_SESSION won't be stored anywhere.
So just use:
session_start();
in both files.

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Ajax getting a value from php?

I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}

Categories

Resources