Jeg foreslår, at du ændrer din tilgang.
Selvom disse eksempelfiler ved første øjekast ser ud af mange, vil du, når du studerer dem, se, at det er en meget mere enkel og logisk tilgang end den retning, du nu er på vej til.
Først skal du flytte db connect / login-tingene til en separat fil og require
eller include
denne fil øverst på hver PHP-side:
INIT.PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Might as well also load your functions page here, so they are always available
require_once('fn/functions.php');
?>
Se nu, hvordan vi bruger det på indeks- (og begrænsede) sider?
INDEX.PHP
<?php
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<!-- Examples need jQuery, so load that... -->
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<!-- and our own file we will create next... -->
<script type="text/javascript" src="js/index.js"></script>
<div id="pageWrap">
<div id="loginDIV">
LoginID: <input type="text" id="liID" /><br>
LoginPW: <input type="password" id="liPW" /><br>
<input type="button" id="myButt" value="Login" />
</div>
</div>
JS/INDEX.JS
$(function(){
$('#myButt').click(function(){
var id = $('#liID').val();
var pw = $('#liPW').val();
$.ajax({
type: 'post',
url: 'ajax/login.php',
data: 'id=' +id+ '&pw=' +pw,
success: function(d){
if (d.length) alert(d);
if (d==1) {
window.location.href = 'restricted_page.php';
}else{
$('#liID').val('');
$('#liPW').val('');
alert('Please try logging in again');
}
}
});
});//END myButt.click
}); //END document.ready
AJAX/LOGIN.PHP
<?php
$id = $_POST['id'];
$pw = $_POST['pw'];
//Verify from database that ID and PW are okay
//Note that you also should sanitize the data received from user
if ( id and password authenticate ){
//Use database lookups ot get this data: $un = `username`
//Use PHP sessions to set global variable values
$_SESSION['username'] = $un;
echo 1;
}else{
echo 'FAIL';
}
RESTRICTED_PAGE.PHP
<?php
if (!isset($_SESSION['username']) ){
header('Location: ' .'index.php');
}
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
<!-- AND here go all teh restricted things you need a login to do. -->
Mere om AJAX - studere de simple eksempler