简体   繁体   中英

How to redirect to another page in php after form is complete?

I have a registration form in a site I am building. If it is filled correctly, I want the user to go back to the main page.

I tried to use header but I get "Cannot modify header information..." I guess this happens because I post to $_SERVER['PHP_SELF'] ;

Any suggestions of how can I redirect the user if the form is ok? (Other than a success page with a button)

You can only use the header() function if no other text/string data has been output by the web server to the users browser.

You'll need to put the logic for the redirect at the top of your script before anything else:

<?php

// Process form

// If processing was successful, redirect
if($success) 
{
    header("Location: http://www.main-page-url.com/");
}

?>

The reason for this is that when a browser receives information from the web server it receives an HTTP header (which the header() function outputs the redirect to), and then outputs the body of the HTTP response after the HTTP header. If your script is echo ing anything before the header command, you'll continue to receive that error.

You get the cannot modify header information message because you are trying to send new headers to the browser after content has been rendered to the page. If you do the header() call before any echo/print calls, it will redirect. Otherwise, you would need a meta redirect. Where you post the form to is irrelevant.

The reason why this doesn't work is that headers precede content in an HTTP request. When you output content, PHP gets ahead of the game by sending all headers and all the content its processed thus far. There's no CTRL+Z for sending HTTP requests, so the header() function can't add headers after they've been sent.

However, you can call header() after content is echoed if you utilize the ob buffering family of functions. Call ob_start() to buffer page output, make any necessary header calls or content outputs, and finally send the output with ob_end_flush() . Ex.

<?php
ob_start(); //Start buffering
?>
<p>This is output!!!</p>
<?php
header('403 Moved Permanently'); //Fancy redirect is fancy
ob_end_flush(); //Send page content with redirect header
?>

The only possible disadvantage to using buffering is that the user will experience a slight hangup in receiving the content until the ob_end_flush() command is called. Most likely this won't be noticeable, though, so you shouldn't worry about it!

Before going through all this, you might consider moving all of your header calls to a place before content is outputted in your code. Also check the opening PHP tag for preceding spaces as they will force headers and content to be sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM