douwei7976 2012-10-11 07:32
浏览 73
已采纳

PHP重定向提交无效

Many thanks in advance for even attempting to present a solution. I'm having trouble with a simple html contact form. The form's method is set to post and it's action is sent to a php file. At the end of the PHP file the form is sent to, there is a basic location:redirection.

ex) header("Location: ../index.htm");

I configured my php.ini file (Apache) to display the php error(s). This is what I'm shown:

"Cannot modify header information - headers already sent by (output started at /home2/jwarddes/public_html/newTest/php/contact.php:2) in /home2/jwarddes/public_html/newTest/php/contact.php on line 20"

Line 20 of my code is my header("location:... redirect. This appears to be fine, yet something keeps throwing an error. Needless to say, I'm stumped.

Could someone please try their hand at a solution or kindly nudge me in the right direction?

Thanks!

  • 写回答

6条回答 默认 最新

  • duanbiao4025 2012-10-11 07:43
    关注

    that is a common problem.

    make sure you do not have any output (even a simple space at the top of the page) as that will send the headers prior to your redirect.

    Possible Solutions are the following.

    ob_start();
    

    in the top of your page and

    ob_end_flush(); 
    

    at the bottom might solve your issue.

    Also, I have this special function below which do a very smart redirect, try it out and let me know :)

    /**
     * redirect()
     * 
     * Attempts to redirect the user to another page.
     * It tries to PHP header redirect, then JavaScript redirect, then try http redirect.
     * The following redirection method is only attempted if the previous redirection method attempt has failed  
     *  
     * @param mixed $url To be redirected to
     * @return nothing
     */
    function redirect($url)
    {
            if (!headers_sent())
            { //If headers not sent yet... then do php redirect
                    header('Location: ' . $url);
                    exit;
            } else
            { //If headers are sent... do java redirect... if java disabled, do html redirect.
                    echo '<script type="text/javascript">';
                    echo 'window.location.href="' . $url . '";';
                    echo '</script>';
                    echo '<noscript>';
                    echo '<meta http-equiv="refresh" content="0;url=' . $url . '" />';
                    echo '</noscript>';
                    exit;
            }
    } //==== End -- Redirect
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退