cakefoot/www/collect.php

47 lines
2.1 KiB
PHP

<?php
/* Get a unique ID from the browser which PHP creates and manages using a browser cookie */
session_start();
/* The log of play history is stored in JSON format in a file in the same directory as this script. If this file doesn't exist yet, it
* will be created at write time. Each session ID is written to its own file to avoid race conditions between multiple sessions
* sharing a single file. */
$history_path = session_id() . "-Play_History.json";
/* Read JSON data from the history path. If the file doesn't exist, is not in JSON format, or any other exception occurs, just set the
* history to an empty array. */
$history = array();
try
{
/* Check for file existence, especially because doing so will avoid a warning being written to the log when the path doesn't
* exist but file_get_contents is used on the path */
if (file_exists($history_path))
{
$history = json_decode(file_get_contents($history_path), true, 512, JSON_THROW_ON_ERROR);
}
}
catch (Exception $e)
{
error_log("Error while reading history path \"$history_path\": $e");
}
/* JSON data containing the user's play history is passed as a POST request from JavaScript in pre_js_dank.js. Remove HTML and PHP
* special characters and limit length of input to 2048 characters to protect against injections. */
$submitted_user_log = array(session_id() => json_decode(file_get_contents("php://input", false, null, 0, 2048), true)["progress"]);
/* Add a timestamp to the log */
$submitted_user_log["timestamp"] = date("Y-m-d H:i:s");
/* Merge the passed play history into the history array, overwriting any existing data at the current session ID, or adding a new
* section to the array if the session ID doesn't exist as a key in the array yet. Write the array to the history path. */
file_put_contents(
$history_path,
json_encode(
array_merge($history, $submitted_user_log),
JSON_PRETTY_PRINT) . "\n");
/* Print the session ID formatted as JSON, so that the JavaScript program can get the ID as a response. */
echo json_encode(array("id" => session_id()));
?>