PHP中的重定向失败

时间:2013-07-09 08:56:54

标签: php redirect window.location

这是PHP中的一段代码,写在一个名为 core.php 的单独文件中,它包含在 register.php

if(($retuserkey = $this->dbcontroller->dbregister($email, $contact)) > 0){  
    //if user was successfuly registered send an email where he can activate his account!
    $this->mailer->sendForReg($email,$hash,$flname);

    echo "<script>alert('An activation link is sent to your email id. Please check you spam folder too. Please follow the link to complete the registration.'); window.location = './registersuccess.php';</script>";

    echo '<META HTTP-EQUIV="Refresh" Content="0; URL=http://www.websiteaddress.com/registersuccess.php">'; 
    $url = "http://www.websiteaddress.com/registersuccess.php";
    if(!headers_sent()) {
    //If headers not sent yet... then do php redirect
        header('Location: '.$url);
        exit;
    } else {
        //If headers are sent... do javascript redirect... if javascript disabled, do html redirect.
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$url.'";';
        echo '</script>';
    }

    mail("emailaddress@gmail.com","Registration $retuserkey",$email,"Subject");
}

重定向之前和之后都会发送电子邮件。两封电子邮件都已收到,但重定向失败。

我做错了什么?

3 个答案:

答案 0 :(得分:0)

必须在发送任何实际输出之前调用

header(),并且在它之前有回声。

答案 1 :(得分:0)

你做不到:

header('Location: '.$url);
exit;

在事情已经echo出现之后:http://php.net/manual/en/function.header.php

如果您移动echo语句,以便仅在重定向未发生时进行打印,那么您应该没问题。

答案 2 :(得分:0)

  header('Location: http://localhost/yourFileName.php');
    exit;
使用

header()函数/ *重定向到当前目录中请求的其他页面* /  header()函数将原始HTTP标头发送到客户端

N.B:使用正确的网址