我试图让我的 admin.php 页面只能由登录的人访问,这样当您未登录时,您将被发送到 index.php。我尝试了一些 if 语句,但它似乎对我不起作用?
loginHTML.html
<form method="POST" action="verification.php" class="loginFields">
<input type="text" name="username" placeholder="Username" autofocus>
<input type="password" name="password" placeholder="Password">
<input type="submit" name="submit" value="Inloggen">
</form>
login.php
// Start new DOMDocument and load html file.
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile("loginHTML.html");
libxml_use_internal_errors(false);
// Haal verification.php op om gegevens te checken.
include_once('verification.php');
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$object = new user();
$object->login($username, $password);
}
// Save DOMDocument with html document.
echo $dom->saveHTML();
验证.php
// Include connection.php om connectie te maken te de database.
include_once('inc/connection.php');
include_once('login.php');
class user{
private $db;
public function __construct(){
$this->db = new connection();
$this->db = $this->db->dbconnect();
}
public function login($username, $password){
$this->db = new Connection();
$this->db = $this->db->dbConnect();
// Als $username en $password gevuld zijn checken op overeenkomst
if(!empty($username) && !empty($password)){
$st = $this->db->prepare("SELECT * FROM users WHERE username=? AND password=?");
$st->bindParam(1, $username);
$st->bindParam(2, $password);
$st->execute();
$result=$st->fetch(PDO::FETCH_ASSOC);
$id=$result['id'];
// Als er een overeenkomst is doorsturen naar admin.php en session aanmaken
if($st->rowCount() == 1) {
$_SESSION['id'] = $result['id'];
$_SESSION['ingelogt'] = $username;
header('location: admin.php');
exit;
} else {
echo "Incorrect username or password";
}
// Als er niks is ingevoerd bij het inlogscherm
} else {
echo "Please enter your username and password";
}
}
}
admin.php
session_start();
// If session is not ingelogt lead back to index.php.
if(!isset($_SESSION['id'])) {
header("location: index.php");
die();
}
最佳答案
不要使用SELECT *
,而是指定列SELECT id
//...
$st->execute();
$row = $st->fetch();
$id = $row['id'];
关于php - 仅可通过登录用户页面访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24766580/