简体   繁体   中英

How to redirect to another page in php using header after outputting message?

I was making an php file in which I have to add after a certain condition is not true. 添加

The problem is that before I have because of this header function is not working and throwing warning:- 之前,我已经因为此标头功能无法正常工作并警告:-

Warning: Cannot modify header information - headers already sent by (output started at C:\\xampp\\htdocs...\\search.php:229) in C:\\xampp\\htdocs...\\search.php on line 291

Please help me with this and if there any other alternative for this please tell except that

javscript method window.location=url;

Sorry, in PHP there is none. You simply can not modify the headers after starting to send the response body.

There are 3 options

  1. Use html meta refresh
  2. As you mentioned use JavaScript
  3. Move you code to a point where you are still able to manipulate the response header

If you use modern frameworks you mostly don't have this issue. Frameworks like Symphony, Laravel, Slim and others are helping you to keep your business (controller) logic separated from your display (view) logic.

For starters I would recommend the Slim framework https://www.slimframework.com . It's well documented and very lightweight.

You can do with this ways:

With refresh and URL, this will wait five seconds to redirect you:

header("refresh:5;url=https://www.google.com.br/");
echo "Redirecting you to Google in 5 seconds.";

Or you can use javascript:

echo '<script language="JavaScript"> alert("Redirecting you to Google BR!");window.location="https://www.google.com.br/";</script><noscript>Click here: <a href="https://www.google.com.br/">aqui</a>.</noscript>';

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