I'm working with AngularJS and PHP backend, and I'm trying to display data of authenticated user, and I have 2 views, one 'login.html' and the other 'info.html', 2 controllers (one for the login function and the other for selecting the user's data) . I implement the authentication phase but for the second step I want that when the user authenticates, it will be redirected to other view (info.html) where all the information of this user will be displayed.
I tried to use session,but it doesn't work and I don't know why.
How can I store user's data from login function and use it in the second controller(second web service)
login.php
<?php
session_start();
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "user");
if(count($data) > 0)
{
$Email=mysqli_real_escape_string($connect, $data->Email);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE (EmailClient = "'.$Email.'" AND mdp= "'.$mdp.'")';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$token = md5($Email.time()."51395+81519851");
$query = "UPDATE client SET token = '".$token."' WHERE EmailClient = '".$Email."'";
mysqli_query($connect , $query);
$_SESSION["logged_in"] = true;
$_SESSION["token"] = $token;
;
$result['message'] ='Logged In';
$result['email'] =$Email;
$result['token'] = $token;
$resultstring=json_encode($result);
$resultstring=str_replace("null", '""', $resultstring);
echo $resultstring;
exit;
}
$result['code'] = 603;
$result['message'] ='The username or password are incorrect!';
$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring;
exit;
}
?>
info.php
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "user");
$output = array();
$query = "SELECT FirstName,FamilyName,EmailClient FROM client WHERE token = '".$_SESSION['token']."'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output[] = $row;
}
echo json_encode($output);
}
?>
loginCtrl
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'Email' : $scope.Email,
'password' : $scope.password
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
$state.go('info');
}
})
.error(function(data, status, headers, config, result)
{
console.log('error');
});
}
});
infoCtrl :
app.controller('infoCtrl', function($scope, $http,$state,$filter){
$scope.loadColis = function(){
$http.get("http://localhost/deb/info.php")
.success(function(data){
$scope.names = data;
});
}
I don't know how get user authenticated data, how can I do please?
Thanks in advance
You need to create a session when the login function is passed without any error, like given below, you have to use $sessionstorage service in controller for this to work.
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config, result) {
console.log(data);
//Here create a session, so I am creating a "user" session with its details
$rootScope.globals = {
currentUser: {
firstname: data.firstname,
lastname: data.lastname,
}
};
$sessionStorage.user = $rootScope.globals;
$state.go('info');
}
})
And then you can get details of the user on info page using $sessionStorage.user.currentUserand again you will need $sessionStorage service in its controller also.
Related
I have a problem that I've been trying to solve for a long time. I have read courses about PHP sessions and I had proposals to use localstorage but to no avail
The problem:
Im working with angularJS and PHP backend, and I have 2 views, one 'login.html' and the other 'info.html', 2 controllers (one for the login function and the other for selecting the user's data) . I managed to do the authentication phase but for the second step I want that when the user authenticates, it will be redirected to other view (info.html) where all the information of this user will be displayed. How can I store the data from login function and use it in the second controller(second web service)
login.php
<?php
session_start();
$_SESSION['token'] = true;
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
if(count($data) > 0)
{
$Email=mysqli_real_escape_string($connect, $data->Email);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE (EmailClient = "'.$Email.'" AND mdp= "'.$mdp.'")';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$token = md5($Email.time()."51395+81519851");
$query = "UPDATE client SET token = '".$token."' WHERE EmailClient = '".$Email."'";
mysqli_query($connect , $query);
$_SESSION["logged_in"] = true;
$_SESSION["token"] = $token;
$_SESSION["Email"] = $Email;
$result['token'] = $token;
$resultstring=json_encode($result);
$resultstring=str_replace("null", '""', $resultstring);
echo $resultstring;
exit;
}
?>
loginCtrl
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'Email' : $scope.Email,
'password' : $scope.password
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
$state.go('info');
}
})
.error(function(data, status, headers, config, result)
{
console.log('error');
});
}
});
infoCtrl :
app.controller('infoCtrl', function($scope, $http,$state,$filter){
$scope.loadColis = function(){
$http.get("http://localhost/deb/info.php")
.success(function(data){
$scope.names = data;
});
}
info.php
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "test");
$output = array();
$query = "SELECT Name,Adresse FROM client WHERE token = '".$_SESSION['token']."'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output[] = $row;
}
echo json_encode($output);
}
?>
I don't know how get user authenticated data, how can I do please?
Thanks in advance
In Login Controller:
app.controller('loginCtrl', function($scope, $location,$state,$http,$window, $cookies){
$scope.submit = function()
{
data = {
'Email' : $scope.Email,
'password' : $scope.password
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
$cookies.putObject('AuthenticateData', data);
$state.go('info');
}
})
.error(function(data, status, headers, config, result)
{
console.log('error');
});
}
});
In Info controller:
app.controller('infoCtrl', function($scope, $http,$state,$filter, $cookies){
//use something like this
var authenticateData = cookies.getObject("AuthenticateData");
});
This is just an example to show how cookies does works. You can work around in it.
I m working on authentification in my application, with AngularJS and PHP backend, in controller I put a console.log, to see if the authentication is working, and I find that everything is alright, when the password and username are incorrect I get error message and when they are wrong , I get that they are incorrect, but in that case, I want to be redirected to other view , when I put : window.location.href = '#/admin'; it redirect me to admin view in the two cases, not only when they are correct. can you help me please:
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'NomClient' : $scope.NomClient,
'mdp' : $scope.mdp
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
window.location.href = '#/admin';
})
.error(function(data, status, headers, config, rsult)
{
console.log('error');
});
}
});
login.php
<?php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "sem1");
if(count($data) > 0)
{
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND mdp= "'.$mdp.'"';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
$result['code'] = 200;
$result['message'] ='Logged In';
}
else
{
$result['code'] = 603;
$result['message'] ='The username or password are incorrect!';
}
$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring ;
}
?>
Thanks in advance
Instead of window.location.href use
$state.go(state_name_of_#/admin)
Refer this $state.go()
The success function calls always when there is response irrespective of authentication.
in your PHP file, return true response only if the authentication success, otherwise return false to the front end
Then check for the response or response.responseMessage in something you will find the returned value.
.success(function(reponse){
var data = JSON.parse(reponse);
if(data.code == 200){
$state.go(enter_your_state_name_of_admin); // example "admin"
} else {
// do nothing
}
})
You can use the $state.go() for this as:
$state.go('admin');
'admin must be your state name.'
EDIT
The code in .success will be executed when ever you get data without any error. If you want to redirect based on the authentication, you need to write code for that seperately. Example code is given below.
.success(function(data, status, headers, config,result) {
console.log(data);
if(data.message === 'Logged In') {
$state.go('admin');
}
})
I try to make an authentication using angualrJS and php. I tested it by console.log, when the password is incorrect I get error message, and when the password is correct I don't get anything, in this case, I want to be riderected to other view, how can I do please:
app.js
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'NomClient' : $scope.NomClient,
'mdp' : $scope.mdp
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config)
{
// $window.location.href = '#/admin';
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log('error');
});
}
});
login.php
<?php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
if(count($data) > 0)
{
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND mdp= "'.$mdp.'"';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
As you see, I have a comment line in app.js: // $window.location.href = '#/admin'; I put it as comment because when I put it, it redirects me to admin view however the password is incorrect.
Thanks in advance
With AngularJS you can use the $location service
$Location - Documentation
Try using:
$location.path("your new path here")
For an example: please refer to the following answer to another post:
https://stackoverflow.com/a/14387747/7018180
Try this code in login.php
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
$result['code'] = 200;
$result['message'] ='Logged In';
}
else
{
$result['code'] = 603;
$result['message'] ='The username or password are incorrect!';
}
$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring ;
die;
And check result code in js if it is 200 then it will be in succes other wise in error.
Change .success\.error to .then(), Change your code like :
$http.post('http://localhost/deb/login.php', data).then(function(response) {
console.log(response.data);
$window.location.href = '#/admin';
}, function(error) {
console.log('error');
});
.success is a property of $http service so if there would be some value in data variable the $window.location is eventually going to get called.. so to improve that you can use if condition inside $http service which would check the passed username and password with the response that it would get from the service and then in if condition you can redirect it to another page.
app.service('AuthenticationService', function ($http, $window){
this.login = function (username, password) {
return $http({
url: 'http://localhost/deb/login.php',
method: 'POST',
params: {
NomClient : username,
mdp : password
}
})
};
});
app.controller('loginCtrl', function ($scope, $state, $http, $window, AuthenticationService, $remember) {
$scope.submit = function()
{
AuthenticationService.login($scope.NomClient,$scope.mdp)
.then(function(response) {
if (response.data.NomClient == $scope.NomClient && response.data.mdp == $scope.mdp)
{
$state.go('application.home');
}
else {
alert('Credentials do not match our records. Please try again.');
}
})
}
});
and instead of $window.location you can use $state.go functionality of angularJS. It would redirect your page to the specific state that would be mentioned and it would look for that state in route file and would execute that state along with its templateUrl and controller.
Here's properly working code for your question tested properly. if you are still looking for a solution
app.js
app.controller('loginCtrl', function ($scope, $http,$state) {
$scope.submit = function ()
{
$scope.data = {
username: $scope.username,
password: $scope.password
}
$http.post('http://localhost/HTML5Application/public_html/login.php', {serviceData: $scope.data})
.success(function (data) {
alert(data);
$state.go('newState');
})
.error(function (data) {
alert("problem with service call");
});
};
});
login.php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "embroidery");
if (count($data) > 0) {
$username = mysqli_real_escape_string($connect, $data->serviceData->username);
$password = mysqli_real_escape_string($connect, $data->serviceData->password);
$query = 'SELECT * FROM `client` WHERE username = "' . $username . '" AND password= "' . $password . '"';
$q = mysqli_query($connect, $query);
if (mysqli_num_rows($q) > 0) {
$_SESSION["logged_in"] = true;
$_SESSION["name"] = $username;
echo $_SESSION["name"];
} else {
echo 'The username or password are incorrect!';
}
}
?>
login.html
<div class="list list-inset" ng-controller="loginCtrl">
<label class="item item-input">
<input type="text" placeholder="Username" required="" ng-model="username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="password">
</label>
<button class="button button-block button-positive" name="submit" ng-click="submit()">Login</button>
</div>
Thank you all, this is the solution of this question, solved by "Mr_Perfect":
we have just to add a condittion in suceess:
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
if(data.code == 200){
$state.go('admin');
}
})
.error(function(data, status, headers, config, rsult)
{
console.log('error');
});
Thanks to you all
I m working with angularJS and php backend, and I try to make an authentication. I tested it by console.log, when the password is incorrect I get error message, and when the password is correct I don't get anything, in this case, I want to be riderected to other view, how can I do please:
app.js
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'NomClient' : $scope.NomClient,
'mdp' : $scope.mdp
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config)
{
// $window.location.href = '#/admin';
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log('error');
});
}
});
login.php
<?php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
if(count($data) > 0)
{
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND mdp= "'.$mdp.'"';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
As you see, I have a comment line in app.js: // $window.location.href = '#/admin'; I put it as comment because when I put it, it redirects me to admin view however the password is incorrect.
Thanks in advance
In the php file
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
$response = array();
if(count($data) > 0)
{
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND mdp= "'.$mdp.'"';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$response["error"] = false;
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
}
else
{
$response['error'] = true;
}
echoRespnse(200, $response);
}
function echoRespnse($status_code, $response)
{
$app->contentType('application/json');
echo json_encode($response);
}
?>
app.js
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'NomClient' : $scope.NomClient,
'mdp' : $scope.mdp
};
$http.post('http://localhost/deb/login.php', data) .success(function(data)
{
console.log(data.error);
if(data.error=="true") {
//Show error
}else {
//else redirect
}
})
.error(function(data)
{
console.log('error');
});
}
});
On Your php page
if(mysqli_num_rows($q) > 0 )
{
echo 'success';
}
else
{
echo 'error';
}
}
On your app.js
$http.post('http://localhost/deb/login.php', data)
.success(function(response)
{
if(response.data =='success'){
$window.location.href = '#/admin';
}else{
console.log('Username or Password Error');
}
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log('error');
});
this problem make me confuse why user still can login although username and password is wrong. I don't have any idea in this problem. i try build android with ionic framework
this my controller
**
.controller('LoginCtrl', function ($scope, kaka, $ionicPopup, $state, Varlogin) {
$scope.loginData = {};
$scope.proseslogin = function () {
kaka.loginUser($scope.loginData.username, $scope.loginData.password).success(function (data) {
if (data.length > 0) {
Varlogin.setObject(data[0]);
var alertPopup = $ionicPopup.alert({
title: 'Selamat Datang',
template: 'Perikasa keadaan motor anda!'
});
$state.go('app.home');
} else {
var alertPopup = $ionicPopup.alert({
title: 'Login Gagal!',
template: 'Periksa Username dan Password anda!'
});
}
}).error(function (data) {
});
};
$scope.register = function () {
$state.go('register');
};
})
**
and this my php
**
if($function == "login" ){
$sql = mysqli_query($con, "select * from login where username='$w5'")or die(mysqli_error($con));
$row = mysqli_fetch_assoc($sql);
$pass = $row['hash_password'];
$hash_password = password_verify($w6, $pass);
if($hash_password == TRUE) {
$sqlcode = $con->query("select * from login where username='$w5' AND hash_password='$pash' AND aktif='Y'", MYSQLI_USE_RESULT);
$jsonObj = array();
while ($result = mysqli_fetch_object($sqlcode)) {
$jsonObj[] = $result;
echo "Berhasil";
}
}else {
echo "gagal";
mysqli_close($con);
}
}
**
please help my problem