What are some best practices for handling form submissions and redirects in PHP to avoid infinite loops?
When handling form submissions and redirects in PHP, it is important to avoid creating infinite loops where the form submission keeps redirecting back to the same page. To prevent this, you can use a session variable to track whether the form has already been submitted and processed. By checking this session variable before processing the form and redirecting, you can ensure that the form is only processed once.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST" && !isset($_SESSION['form_submitted'])) {
// Process form submission
// Redirect to another page after processing
$_SESSION['form_submitted'] = true;
header("Location: success.php");
exit();
}
?>