What is the best practice for opening a form in the same window after submission in PHP?
When submitting a form in PHP, it is a best practice to redirect back to the same page after processing the form data to prevent resubmission on page refresh. This can be achieved by using the header() function to redirect back to the same page.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Process form data here
// Redirect back to the same page to prevent form resubmission
header("Location: ".$_SERVER['PHP_SELF']);
exit();
}
?>
<!-- Your HTML form goes here -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<!-- Form fields go here -->
<input type="submit" value="Submit">
</form>
Related Questions
- How can PHP developers ensure that their code is properly organized and categorized within a forum or discussion platform?
- How can developers ensure consistent text formatting across different platforms when using nl2br() in PHP?
- What are the advantages and disadvantages of embedding PHP code within HTML versus separating them into different blocks?