如何用fopen()和fwrite()将用户登录数据转为JSON数组带换行写入文件?
fopen() and fwrite() Got it, let’s break down exactly how to capture your user’s login details, structure them into a JSON array, and write that data to a file with proper line breaks using PHP’s fopen() and fwrite().
Step 1: Capture All Required Login Data
First, let’s make sure we’re collecting all the fields you mentioned (user-agent, IP, timestamp, OS, etc.). We’ll also add a helper function to parse the operating system from the user agent string:
// Collect core login data $loginEntry = [ 'user_id' => $userRow['user_id'], 'login_timestamp' => $date->getTimestamp(), // Assumes $date is a valid DateTime object 'login_ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'operating_system' => getOperatingSystem($_SERVER['HTTP_USER_AGENT']) ]; // Helper function to detect OS from user agent function getOperatingSystem($userAgent) { $osMatches = [ '/windows nt 10/i' => 'Windows 10', '/windows nt 6.3/i' => 'Windows 8.1', '/windows nt 6.2/i' => 'Windows 8', '/windows nt 6.1/i' => 'Windows 7', '/macintosh|mac os x/i' => 'macOS', '/linux/i' => 'Linux', '/ubuntu/i' => 'Ubuntu', '/android/i' => 'Android', '/iphone/i' => 'iOS (iPhone)', '/ipad/i' => 'iOS (iPad)', '/blackberry/i' => 'BlackBerry', '/webos/i' => 'WebOS' ]; foreach ($osMatches as $regex => $osName) { if (preg_match($regex, $userAgent)) { return $osName; } } return 'Unknown OS'; }
Step 2: Handle the JSON File (Create or Update)
Next, we need to either create a new JSON file (if it doesn’t exist) or update the existing one by adding our new login entry to the array. Here’s how to do that with fopen() and fwrite():
// Define your user folder and login file path $userFolder = $_SERVER['DOCUMENT_ROOT'] . '/account/users/' . $auth_user->user_folder_name($userRow["user_id"], $userRow["username"]) . '/'; $loginFile = $userFolder . $userRow['username'] . '_login_history.json'; // Initialize the login array $loginHistory = []; // If the file exists, read and parse its current content if (file_exists($loginFile)) { $existingContent = file_get_contents($loginFile); $loginHistory = json_decode($existingContent, true); // Fallback to empty array if JSON parsing fails if (!is_array($loginHistory)) { $loginHistory = []; } } // Add the new login entry to the array $loginHistory[] = $loginEntry; // Convert the array to formatted JSON (with line breaks and indentation) $formattedJson = json_encode($loginHistory, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); // Write the JSON to the file using fopen() and fwrite() $fileHandle = fopen($loginFile, 'w'); if ($fileHandle) { // Write the JSON content plus a trailing newline for cleanliness fwrite($fileHandle, $formattedJson . PHP_EOL); fclose($fileHandle); // Optional: Confirm success // echo "Login history updated successfully!"; } else { // Handle error if file can't be opened // echo "Error: Unable to open login file for writing. Check folder permissions."; }
Key Details to Note
JSON_PRETTY_PRINT: This flag ensures your JSON is human-readable with proper line breaks and indentation—exactly what you asked for.PHP_EOL: Uses the correct newline character for your server’s OS (Windows uses\r\n, Unix uses\n), making the file compatible across systems.- File Mode: We use
'w'(write mode) here because we’re replacing the entire file with the updated array. If you wanted to append a single JSON object per line (not a valid array), you could use'a'(append mode), but that wouldn’t be a standard JSON array. - Permissions: Make sure the
$userFolderdirectory has write permissions set (typically755or775depending on your server setup), otherwisefopen()will fail.
Example Output JSON
Your login file will look something like this, with each entry on its own line (formatted for readability):
[ { "user_id": 123, "login_timestamp": 1699999999, "login_ip": "192.168.1.1", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "operating_system": "Windows 10" }, { "user_id": 123, "login_timestamp": 1700000000, "login_ip": "10.0.0.1", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15", "operating_system": "macOS" } ]
内容的提问来源于stack exchange,提问作者JamesBond

