Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear

Stuck with a problem? Got Error? Ask AI support!

Copy Clear
Copy Format Clear
<?php session_start(); // Function to calculate required speed function calculateSpeed($speedAhead, $timeElapsed) { $distanceAhead = 40; // Given distance if ($timeElapsed <= 0) { return "Error: Time elapsed must be greater than 0."; } $requiredSpeed = ($distanceAhead + ($speedAhead * $timeElapsed)) / $timeElapsed; return number_format($requiredSpeed, 2) . " km/h"; } // Function to store historical data function storeHistory($speedAhead, $timeElapsed, $requiredSpeed) { return [$speedAhead, $timeElapsed, $requiredSpeed]; } // Function to write data to file function writeToFile($history) { $file = fopen("history.txt", "a"); foreach ($history as $entry) { fwrite($file, implode(", ", $entry) . "\n"); } fclose($file); } // Initialize session history if (!isset($_SESSION['history'])) { $_SESSION['history'] = []; } $requiredSpeed = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $speedAhead = isset($_POST["speedAhead"]) ? (float) $_POST["speedAhead"] : 0; $timeElapsed = isset($_POST["timeElapsed"]) ? (float) $_POST["timeElapsed"] : 0; // Input validation if ($speedAhead < 0 || $timeElapsed <= 0) { $requiredSpeed = "Error: Invalid input. Speed must be >= 0, and time must be > 0."; } else { $requiredSpeed = calculateSpeed($speedAhead, $timeElapsed); $historyEntry = storeHistory($speedAhead, $timeElapsed, $requiredSpeed); $_SESSION['history'][] = $historyEntry; writeToFile([ $historyEntry ]); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Catch-Up Speed Calculator</title> </head> <body> <h2>Catch-Up Speed Calculator</h2> <form method="POST"> <label for="speedAhead">Speed of Car Ahead (km/h):</label> <input type="number" step="0.1" name="speedAhead" required><br><br> <label for="timeElapsed">Time Elapsed (hours):</label> <input type="number" step="0.1" name="timeElapsed" required><br><br> <button type="submit">Calculate</button> </form> <?php if (!empty($requiredSpeed)) { ?> <h3>Result:</h3> <p>Required speed to catch up: <strong><?php echo $requiredSpeed; ?></strong></p> <?php } ?> <h3>History:</h3> <table border="1"> <tr> <th>Speed Ahead (km/h)</th> <th>Time Elapsed (hours)</th> <th>Required Speed (km/h)</th> </tr> <?php foreach ($_SESSION['history'] as $entry) { ?> <tr> <td><?php echo $entry[0]; ?></td> <td><?php echo $entry[1]; ?></td> <td><?php echo $entry[2]; ?></td> </tr> <?php } ?> </table> </body> </html>
Copy Clear