doubao12345 2017-06-11 03:04
浏览 33
已采纳

如果指定了<html>标签,PHP重定向将失败[重复]

This question already has an answer here:

<html>
<body>
<?php
    error_reporting(E_ALL | E_WARNING | E_NOTICE);
    ini_set('display_errors', TRUE);
    if( $_SERVER['REQUEST_METHOD'] == 'POST') {
        header('Location: https://www.google.com/', true, 302);
    exit();
    }
?>
<form method='post'>
<input type='submit' name='submit' value='Submit' /><br />
</form>
</body>
</html>

The form works as expected if the "html" and "body" tags are removed. The presence of either one of them causes failure. This occurs on one hosting site; however I can run it on another host without any problems.

Are there any settings in php.ini that could cause this behavior?

When the code runs with the "html" or "body" tags, this error is displayed: Warning: Cannot modify header information - headers already sent by (output started at /webroot/m/o/montc001/primary/www/test.php:3) in /webroot/m/o/montc001/primary/www/test.php on line 7

The site that fails, also has Wordpress installed. The WP site is being replaced by a new implementation.

</div>
  • 写回答

1条回答 默认 最新

  • dongyuan2652 2017-06-11 03:14
    关注

    Your header function has to be at the top and called before any html is printed out.

    From the php.net documentation (http://php.net/manual/en/function.header.php) :

    Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

    So your code should be something like:

    <?php
        error_reporting(E_ALL | E_WARNING | E_NOTICE);
        ini_set('display_errors', TRUE);
        if( $_SERVER['REQUEST_METHOD'] == 'POST') {
            header('Location: https://www.google.com/', true, 302);
        exit();
        }
    ?>
    <html>
    <body>
    <form method='post'>
    <input type='submit' name='submit' value='Submit' /><br />
    </form>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题