You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP硬编码用户名密码登录页开发及留言板项目技术咨询

Alright, let's break down your needs and solve them step by step:

1. Hardcoded Username/Password Login Page (login.php)

This will be a simple login system that checks against fixed credentials, and uses sessions to keep the user logged in for restricted actions (like deleting posts).

Here's the complete code for login.php:

<?php
session_start();
// Hardcoded credentials - adjust these to your preferred values
$valid_username = "admin";
$valid_password = "guestbook123";

// Handle login submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);

    if ($username === $valid_username && $password === $valid_password) {
        $_SESSION["logged_in"] = true;
        // Redirect back to guestbook after successful login
        header("Location: index.php");
        exit;
    } else {
        $error = "Invalid username or password!";
    }
}
?>
<!DOCTYPE html>
<html lang="sv">
<head>
    <meta charset="utf-8">
    <title>Administration Login</title>
    <link rel="stylesheet" href="css/stilmall.css?<?php echo time(); ?>" type="text/css">
</head>
<body>
<nav id="mainmenu">
    <ul>
        <li><a href="index.php">Home</a></li>
        <li><a href="login.php">Administration</a></li>
    </ul>
</nav>
<div class="login-form">
    <h3>Login to Manage Guestbook</h3>
    <?php if (isset($error)) echo "<p style='color:red'>$error</p>"; ?>
    <form method="post" action="login.php">
        Username: <input type="text" name="username" required>
        <br><br>
        Password: <input type="password" name="password" required>
        <br><br>
        <input type="submit" value="Login">
    </form>
</div>
</body>
</html>

Key Notes:

  • We use session_start() to track the user's login state. Once logged in, $_SESSION["logged_in"] will be set to true.
  • After successful login, we redirect back to the guestbook index to avoid form resubmission issues.
  • Added trim() to clean up user input and required attributes to enforce form field completion.

2. Complete Your Guestbook index.php Code

Your existing code was missing the full post display logic, and the delete functionality was commented out. Let's fix that, plus restrict admin actions to logged-in users only.

Here's the updated index.php:

<?php 
error_reporting(-1); 
ini_set("display_errors", 1); 
session_start(); // Start session to check login state
?>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title>Guestbook</title>
</head>
<link rel="stylesheet" href="css/stilmall.css?<?php echo time(); ?>" type="text/css">
<body>
<nav id="mainmenu">
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="login.php">Administration</a></li>
<?php if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"]): ?>
    <li><a href="logout.php">Logout</a></li>
<?php endif; ?>
</ul>
</nav>
<div class="posts">
<h3>Add post:</h3>
<?php 
include("includes/config.php");
$user = new Users();

// Enable delete functionality (only for logged-in admins)
if(isset($_GET['deleteid']) && isset($_SESSION["logged_in"]) && $_SESSION["logged_in"]) {
    $id = $_GET['deleteid'];
    if($user->deleteUser($id)) {
        echo "<p style='color:green'>Post Deleted Successfully</p>";
    } else {
        echo "<p style='color:red'>Error: Could not delete post</p>";
    }
}

// Handle new post submission
if(isset($_POST["submit"])) {
    $name = trim($_POST["name"]);
    $post = trim($_POST["post"]);
    
    // Basic validation to prevent empty posts
    if(!empty($name) && !empty($post)) {
        if( $user->addUser($name, $post)) {
            echo("<p style='color:green'>Post added to the board! </p>");
        } else {
            echo("<p style='color:red'>Error: Could not add post</p>");
        }
    } else {
        echo("<p style='color:red'>Please fill in both your name and post content!</p>");
    }
}
?>
<form method="post" action="index.php">
Username: <input type="text" name="name" required>
<br><br>
Content: <textarea name="post" rows="4" cols="50" required></textarea>
<br><br>
<input type="submit" value="Add Post" name="submit">
</form>
<h3>Existing Posts</h3>
<?php 
// Fetch and display all posts
$userlist = $user->getUsers();
if(empty($userlist)) {
    echo "<p>No posts yet! Be the first to share something.</p>";
} else {
    foreach($userlist as $c) {
        echo "<div class='post-item'>";
        // Use htmlspecialchars to prevent XSS attacks
        echo "<strong>" . htmlspecialchars($c["name"]) . "</strong>: " . htmlspecialchars($c["post"]);
        // Show delete button only if user is logged in
        if(isset($_SESSION["logged_in"]) && $_SESSION["logged_in"]) {
            echo " <a href='index.php?deleteid=" . $c["id"] . "' onclick='return confirm(\"Are you sure you want to delete this post?\")'>Delete</a>";
        }
        echo "</div><br>";
    }
}
?>
</div>
</body>
</html>

Key Improvements:

  1. Session Integration: Added session_start() to check login status, and only show the delete button/logout link to authenticated admins.
  2. Post Display: Completed the foreach loop to show both the poster's name and message, using htmlspecialchars() to block XSS attacks.
  3. Form Upgrade: Swapped the post input to a <textarea> for better user experience, and added basic validation for empty submissions.
  4. Delete Protection: Restricted the delete feature to logged-in users and added a confirmation prompt to avoid accidental deletes.

3. Optional: Logout Page (logout.php)

To let users end their admin session, create a simple logout.php:

<?php
session_start();
session_destroy(); // Clear all session data
header("Location: index.php");
exit;
?>

Quick Security Reminders:

  • Hardcoded credentials are fine for testing or small personal projects, but never use them in production. For real-world apps, store hashed passwords in a database.
  • Ensure your Users class uses prepared statements for all database queries to prevent SQL injection. Never concatenate user input directly into SQL strings.

内容的提问来源于stack exchange,提问作者Palmoz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:00:41