Secure Member-Only Pages with a Login System
When creating a secure login system for member-only pages, there are several aspects to consider. Here's an alternative approach to address your concerns:
Separate Initialization and Functions
Centralized Login Processing
Session Management
Page Content and Template Inclusion
Example implementation:
init.php (database and function initialization)
<?php // Database connection $servername = "localhost"; $username = "username"; $password = "password"; $db = "database"; // Create connection $conn = new mysqli($servername, $username, $password, $db); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Load custom functions require_once('fn/functions.php');
index.php (login page)
<?php require_once('inc/head.inc.php'); require_once('fn/init.php'); ?> <div>
ajax/login.php (login processing)
<?php $username = $_POST['username']; $password = $_POST['password']; // Validate credentials against database if (authenticate($username, $password) == true) { // Set session variables session_start(); $_SESSION['username'] = $username; echo 1; // Success } else { echo 'Invalid credentials.'; }
restricted_page.php (protected page)
<?php require_once('inc/head.inc.php'); require_once('fn/init.php'); // Check if user is logged in session_start(); if (!isset($_SESSION['username'])) { header('Location: index.php'); exit; } %> <h1>Welcome to the Restricted Page, <?php echo $_SESSION['username']; ?>!</h1>
By following these guidelines, you can create a secure login system that protects member-only pages from unauthorized access.
The above is the detailed content of How to Secure Member-Only Pages with a Login System?. For more information, please follow other related articles on the PHP Chinese website!