Simple PHP Post-Redirect-Get code example
Simplest scenario:
if ($_POST) {
// Execute code (such as database updates) here.
// Redirect to this page.
header( "Location: {$_SERVER['REQUEST_URI']}", true, 303 );
exit();
}
Use REQUEST_URI
. Do not use PHP_SELF
as in most CMS systems and frameworks PHP_SELF
would refer to /index.php
.
A snippet of code:
if (count($_POST)) {
// process the POST data
// your code here- so for example to log a user in, register a new account..
// ...make a payment...etc
// redirect to the same page without the POST data, including any GET info you
// want, you could add a clause to detect whether processing the post data has
// been successful or not, depending on your needs
$get_info = "?status=success";
// if not using rewrite
// header("Location: ".$_SERVER['PHP_SELF'].$get_info);
// if using apache rewrite
header("Location: ".$_SERVER['REQUEST_URI'].$get_info);
exit();
}
Browser
HTML form
method=POST
|
v
PHP app
reads $_POST
sends 303 header
|
v
Browser
receives header
redirected to
new page
|
v
PHP app
reads $_GET
does whatever
A common use is in login authentication. That's the process flow when user submits the login form. PHP app authenticates user via $_POST vars. Sends a 303 header back to browser when the user has successfully authenticated. So user is redirected to a new page.