How can simple interactions with PHP sessions be implemented for a number-guessing game?

To implement simple interactions with PHP sessions for a number-guessing game, you can store the target number in a session variable and update it as needed during the game. You can also store the user's guesses in a session array and check them against the target number. This allows you to keep track of the game state across multiple page loads.

<?php
session_start();

// Check if the target number is already set in the session
if (!isset($_SESSION['target'])) {
    // Generate a random number between 1 and 100 as the target number
    $_SESSION['target'] = rand(1, 100);
}

// Check if the user has submitted a guess
if (isset($_POST['guess'])) {
    $guess = $_POST['guess'];

    // Add the guess to the session array
    $_SESSION['guesses'][] = $guess;

    // Check if the guess is correct
    if ($guess == $_SESSION['target']) {
        echo "Congratulations! You guessed the correct number.";
        // Reset the game by unsetting the target number and guesses
        unset($_SESSION['target']);
        unset($_SESSION['guesses']);
    } elseif ($guess < $_SESSION['target']) {
        echo "Try a higher number.";
    } else {
        echo "Try a lower number.";
    }
}
?>

<form method="post">
    <label for="guess">Enter your guess (1-100):</label>
    <input type="number" name="guess" min="1" max="100" required>
    <button type="submit">Submit Guess</button>
</form>