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

PHP用户信息记录程序异常求助:提示输入用户名且功能失效

Troubleshooting Your PHP User Input Logger

Hey there! Let's work through the issues you're having with your PHP script—sounds like we've got a few small tweaks to get it working as expected. Let's break them down one by one:

1. Only "Please Enter Username" Shows + Background Color Not Working

The most likely culprit here is that your script isn't outputting a complete HTML document. Browsers need proper structure (like <head> and <body> tags) to render styles and content correctly. If you're just echoing the prompt without wrapping it in a full HTML skeleton, the browser won't apply your background color, and you'll only see that plain text.

2. Inputs Not Saving to TXT File (No Manual File Created)

PHP's file_put_contents() will create a file automatically if it doesn't exist, but only if:

  • The directory where you're trying to create the file has write permissions for the web server user (usually www-data on Linux systems).
  • You're using a correct file path (relative paths can be tricky if your script is in a subdirectory).

Fixed Example Script

Here's a complete, working version that addresses all these issues:

<?php
// Handle form submission when user clicks "Submit"
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and get input values
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    
    if (!empty($username) && !empty($password)) {
        // Use absolute path to avoid directory confusion
        $logFilePath = __DIR__ . '/user_records.txt';
        // Format log entry with timestamp (never store plain passwords!)
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $logEntry = date('Y-m-d H:i:s') . " | Username: $username | Hashed Password: $hashedPassword\n";
        
        // Try writing to file (create if missing, append new entries, lock to prevent conflicts)
        if (file_put_contents($logFilePath, $logEntry, FILE_APPEND | LOCK_EX)) {
            $feedback = "Your details have been recorded successfully!";
            $feedbackType = "success";
        } else {
            $feedback = "Oops! Failed to save your details. Check if the directory has write permissions.";
            $feedbackType = "error";
        }
    } else {
        $feedback = "Please fill in both username and password!";
        $feedbackType = "error";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Input Logger</title>
    <style>
        /* Background color applied properly here */
        body {
            background-color: #e6f7ff;
            font-family: 'Arial', sans-serif;
            padding: 2rem;
        }
        .form-wrapper {
            max-width: 400px;
            margin: 0 auto;
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .input-group {
            margin-bottom: 1rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: bold;
        }
        input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 0.75rem;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
        }
        button:hover {
            background-color: #1976D2;
        }
        .feedback {
            margin: 1rem 0;
            padding: 1rem;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="form-wrapper">
        <h2>Enter Your Credentials</h2>
        <?php if (isset($feedback)): ?>
            <div class="feedback <?php echo $feedbackType; ?>">
                <?php echo $feedback; ?>
            </div>
        <?php else: ?>
            <p>Please Enter Username and Password</p>
        <?php endif; ?>
        <form method="post" action="">
            <div class="input-group">
                <label for="username">Username:</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="input-group">
                <label for="password">Password:</label>
                <input type="password" id="password" name="password" required>
            </div>
            <button type="submit">Submit</button>
        </form>
    </div>
</body>
</html>

Key Fixes Explained

  • Complete HTML Structure: The script now outputs a full HTML document with <head> (for styles) and <body> tags, so your background color will render correctly.
  • Absolute File Path: Using __DIR__ ensures the TXT file is created in the same directory as your PHP script, avoiding path confusion.
  • Permission Check: The script checks if file_put_contents() succeeds and gives clear feedback if it fails (usually due to permissions).
  • Security First: I added password_hash() to encrypt passwords—never store plain text passwords in logs or databases, this is a critical security practice.
  • Input Sanitization: trim() removes extra whitespace from inputs, and we validate that both fields are filled before writing to the file.

Permission Troubleshooting

If the file still isn't created:

  • On a Linux server, run chmod 755 /path/to/your/script/directory to give the web server write access.
  • If you're using a shared host, check your control panel (like cPanel) to adjust directory permissions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:45:23