我正在尝试使用 angularjs、php 和 mysql 创建一个简单的应用程序。
我有一个使用 angularjs、PDO 和 mysql 的登录页面。
但是我不确定我这样做是对还是相反..
是否仍然可以使用 $_SESSION
来验证用户登录。还是应该使用 angularjs 身份验证?我对angularjs还是个新手,所以我不知道在angularjs中是否有类似$_SESSION
的代码。
我只需要你们的建议。
提前致谢。
这是我的代码。
HTML 登录
include "lib/connection.php";
if(isset($_SESSION['logged_in'])){
if($_SESSION['logged_in'] == '1'){
header('location:index.php');
}
}
?>
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Implementing AngularJS</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/custom.css">
</head>
<body>
<div class="container" ng-controller="AppCtrl">
<div class="login col-md-4 col-md-offset-4">
<h2>Please Log in</h2>
<form>
<input type="text" name="username" class="form-control" placeholder="Username" ng-model="users.username" />
<input type="password" name="password" class="form-control" placeholder="Password" ng-model="users.password" />
<input type="submit" name="cmd_btn" class="btn btn-primary btn-block" ng-click="login()" />
</form>
<br />
<div class="alert alert-danger" ng-if="message">
<p>Invalid Username or Password!</p>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="controller.js"></script>
</body>
</html>
ANGULARJS 代码
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$window','$scope', '$http', function($window, $scope, $http) {
$scope.login = function(){
console.log($scope.users);
var inputs = 'myData=' + JSON.stringify($scope.users);
$http({
method:'POST',
url:'lib/login_c.php',
data: inputs,
headers:{'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(res){
console.log(res);
if(res == 1){
$window.location.href = "index.php";
}else{
$scope.message = true;
}
});
};
}]);
PHP 代码
<?php
include "connection.php";
if(isset($_POST['myData'])){
$login_obj = json_decode($_POST['myData']);
if(!empty($login_obj->username) AND !empty($login_obj->password)){
$instantiate_login_c = new login_c;
$condition = "username = :username AND password = :password";
$arr = array('username' => $login_obj->username, 'password' => $login_obj->password);
$result = $instantiate_login_c->getWhere('users', $condition, $arr);
if($result){
$_SESSION['logged_in'] = '1';
echo 1;
}else{
echo 0;}
}else{
echo 0;
}
}
最佳答案
是的,这没关系,你可以两种方式都做,但以 Angular 方式做肯定是最好的方法。
关于javascript - AngularJS 和 PHP 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32155114/