Immediate restart after form submission

I need to write a simple program that checks for odd or even numbers in PHP. When I enter a number in a form and click submit, it outputs the correct result for a second and then restarts the page. But when I use XAMPP, it doesn’t restart the page. Is there a way to make it behave the same way?

Repl link/Link to where the bug appears:
https://replit.com/@maximbordyug2/PHPLab3

Screenshots, links, or other helpful context:

  <form method="post" >
      <label for="number">Enter a number:</label>
      <input type="number" id="number" name="number">
      <button type="submit">Submit</button>
    </form>
     <?php
    function OddEven($number) {
      if($number % 2 == 0)
      {
         echo '<p>Number is even</p>';
      }
      else
      {
        echo '<p>Number is odd</p>';
      }
    }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $number = (int)$_POST['number'];
        OddEven($number);
        // echo "<p>Result: </p>";
      }

I think this is because of how replit handles the execution of web applications, it might be refreshing the page after a form submission…

To make it consistent, you can modify your code to prevent the form from being resubmitted upon page reload by utilizing PHP sessions, for example:

<?php
session_start();

function OddEven($number) {
  if($number % 2 == 0) {
     return 'Number is even';
  } else {
    return 'Number is odd';
  }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $number = (int)$_POST['number'];
  $_SESSION['result'] = OddEven($number);
  header('Location: ' . $_SERVER['PHP_SELF']);
  exit();
}

?>

<!DOCTYPE html>
<html>
<head>
  <title>PHP Test</title>
</head>
<body>
  <form method="post">
    <label for="number">Enter a number:</label>
    <input type="number" id="number" name="number" required>
    <button type="submit">Submit</button>
  </form>

  <?php
  if (isset($_SESSION['result'])) {
    echo '<p>' . $_SESSION['result'] . '</p>';
    unset($_SESSION['result']);
  }
  ?>

</body>
</html>
4 Likes

Thank you, I will consider it. I started using XAMPP, which doesn’t have this issue. I think there should be a button that I could turn off for it to start working properly :slight_smile:

2 Likes