I am trying to redirect a page after successful execution. However, I want to display a message to the user (e.g. 'Changed made. Redirecting...') while the redirection is done. Changing header
variables after output in the page causes errors in PHP and I know this. My question is, how should I do this?
My current code is something like
// ... execution code
echo 'Changes made successfully. Now redirecting...';
header('Location: index.php');
and this doesn't work. I have also seen an answer on SO suggesting I use ob_start()
and ob_flush()
at the start and end of my page, respectively. But that didn't solve my problem either, I still get the error.
NB I need to use PHP only, I don't want JavaScript for redirection.
Edit: I ended up using JavaScript for redirection, as I needed to output some useful message to the user before redirecting, and PHP alone isn't the best solution for that.
PHP 301 Redirect To set a permanent PHP redirect, you can use the status code 301. Because this code indicates an indefinite redirection, the browser automatically redirects the user using the old URL to the new page address.
In PHP, when you want to redirect a user from one page to another page, you need to use the header() function. The header function allows you to send a raw HTTP location header, which performs the actual redirection as we discussed in the previous section.
For displaying alert message after redirection you may use Session or QueryString and on page Load check if the Session or QueryString is not empty then display alert message.
The header function in PHP can be used to redirect the user from one page to another. It is an in-built function that sends raw HTTP header to the destination (client). The 'header_value' in the function is used to store the header string. The 'replace_value' parameter stores the value that needs to be replaced.
first, you cant use "header" after echo or any output. second, why you need php for it? you can use javascript or best, just put it in the html like it says here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With