cakefoot/www/collect.php

36 lines
1.4 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. */
$history_path = "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. */
try
{
$history = json_decode(file_get_contents($history_path), true, 512, JSON_THROW_ON_ERROR);
}
catch (Exception $e)
{
$history = array();
}
/* JSON data containing the user's play history is passed as a POST request from JavaScript */
$submitted_user_log = array(session_id() => json_decode(file_get_contents("php://input"), true)["progress"]);
/* 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()));
?>