【问题标题】:phpmailer causing Cross-Origin Request Blocked on Hostingphpmailer 导致跨域请求在主机上被阻止
【发布时间】:2015-02-21 15:58:33
【问题描述】:

我是新手移动开发人员,我使用 phonegap 作为我的框架,也使用 firebug 来帮助我查找遇到的错误/错误。

我收到了这个错误(我在萤火虫上遇到过):

跨域请求被阻止:同源策略不允许.....

这是我的代码(在服务器端,因为可能罪魁祸首是 phpmailer 和 ajax):

PHPMailer:

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");
header("Content-Type: text/html; charset=UTF-8");

include 'db_connect.php';

$applicantEmail = $_POST['PHPRequestor'];
$forgottenPass = '';

    //for checking email
    $q = "SELECT * FROM user WHERE email = '".$applicantEmail."'";

    $result = mysqli_query($con, $q);

    if ($result->num_rows == 0) {

        echo "no email";    

    } else if ($result->num_rows == 1) {

        while ($row = $result->fetch_array(MYSQLI_ASSOC)) {

            $forgottenPass = $row["pw"];

        }

        require_once ('class_email/PHPMailerAutoload.php');                                         //include library phpmailer using auto load
        /*
        require_once 'class_email/class.phpmailer.php';                             
        require_once 'class_email/class.smtp.php';
        */

        $mail             = new PHPMailer();

        $body             = 
        "<body style='margin: 5px;'>

        <br/>
        <strong> 'Forgot Password' </strong> :
        <br/>

        <div style='width: 320px; border:#000000 solid 2px;'>

        Your pass : <strong> ".$forgottenPass." </strong> <br/>

        </div>

        <br/>
        Thanks
        <br/>

        </body>";
        $body             = eregi_replace("[\]",'',$body);


        $mail->IsSMTP();                                                            //Using SMTP

        //Activated debug SMTP to see http response
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages

        //$mail->SMTPDebug      = 2;  

        $mail->SMTPAuth     = true;                                                 //Authentication
        $mail->SMTPSecure   = "tls"; 

        // sets the prefix to the
        $mail->Host         = "smtp.gmail.com";                                     //Set GMAIL as the SMTP  
        $mail->Port         = 587;                                                  //Set the SMTP port for the GMAIL server


        $mail->Username     = "myemail@email.com";                                  //Email
        $mail->Password     = "thepassword";                                        //Password 

        //This will add 'Your Name' to the from address, so that the recipient will know the name of the person who sent the e-mail.
        $mail->SetFrom("myemail@email.com", "Request Forgot Password");             
        $mail->AddReplyTo("myemail@email.com", "Request Forgot Password"); 
        $mail->Subject      = "Request Forgot Password', user : ".$applicantEmail; 
        $mail->MsgHTML($body);

        $address = "targetemail@email.com";                                         //target email
        $mail->AddAddress($address, "'Permintaan Lupa kata sandi'");                    

        if($mail->Send()) {

            echo "success";

        } else {

            echo "Oops, Mailer Error: " . $mail->ErrorInfo;
            exit;

        }

    }

$con->close();

?>

Ajax(使用 jquery)

function sendForgotPassword(FPEmail) { 

    var requestor = FPEmail;

    //create form_data for post data on ajax PHP
    var form_data = new FormData();
    form_data.append("PHPRequestor", requestor);

    $.ajax ({

        type: "POST",
        url: to_phpSide,

        data: form_data,
        contentType : false,
        processData : false,
        beforeSend: function() {

            loadingPageW(1);

        },
        success: function(data){

            if (data == 'success') {
                //when success

            } else if (data == 'no email') {
                //when no email 
            } else {
                //when error or something else occured
            }
        }, //for error message
        error: function (xhr, errorStats, errorMsg) {

            alert("error: "+xhr.errorStats+" , "+errorMsg);


        },
        complete: function() {

            loadingPageW(2);

        }

    });

};

我已经在 localhost 中尝试过并且运行良好。 但是当我尝试托管时,我遇到了错误(在顶部)。

我真的很好奇,如果错误是因为我的页面试图请求跨域的东西, 那么为什么在其他页面上(我使用相同的方法,但没有 phpmailer)在托管上工作得很好?

有什么错误吗?还是我想念的方法?

仅供参考:

  1. 我已经检查了我的主机上的 SMTP (phpmailer) 支持,并且支持良好。

  2. 我没有将html页面放在主机中,我只是将.php放在主机中

  3. 我也已经尝试过了:How to specify the SMTP server in PHPMailer?

但仍然没有机会。

谢谢, 任何帮助将不胜感激:)


-编辑: 在我的萤火虫(控制台)上没有错误,我已经激活了$mail-&gt;SMTPDebug = 2;,但我看不到错误或其他东西,响应只是空的(什么都没有) 我只是看到了

跨域请求被阻止:同源策略不允许.....


-编辑 2: 通过请求@synchro 关于导致错误的 URL,以下是完整的错误:

跨域请求被阻止:同源策略不允许读取 http://myhost/www/myphp 上的远程资源。这可以通过 将资源移动到同一域或启用 CORS。

注意: myhost 是指我用于托管的页面。 myphp 是包含上述代码的 .php 文件(PHPMailer 代码)

【问题讨论】:

  • 这与PHPMailer无关。 PHPMailer 完全在服务器端运行,跨域错误在客户端。 Firebug 应该向您显示被拒绝的请求的 URL,并且该信息对于诊断您的问题至关重要。
  • @Synchro 感谢您指出这里发生的事情。 :) 所以我的客户端是导致这个错误的那个(跨域请求被阻止)? - 查看我对诊断问题所需的 URL 的更新
  • 就像错误所说的那样 - 将它正在访问的 URL 移动到您的域,它将不再是跨域的。
  • 感谢您提供解决方案,但我仍然对您的解决方案有些困惑。你说的“网址”是“http://myhost/www/myphp”?或我使用的本地 URL(因为我使用 HTML(在 localhost 中)来访问我的 .php 在托管中)。我只是想知道,是否有任何解决方案可以在不移动 URL(也没有 JSONP)的情况下克服该错误?无论如何谢谢@Synchro :)

标签: php ajax phpmailer


【解决方案1】:

如果您从http://localhost/index.php 提供您的页面并且它与http://somewhereelse/index.php 对话,那么这是跨域的,因为域不匹配。您可以通过多种方式解决这个问题:

  • 按照其他人的描述设置 access-control 标头
  • 在您自己的服务器上代理请求,使其不会在浏览器中显示为跨域。
  • 在您自己的服务器上执行目标脚本所做的任何事情

最后一个是最简单的。

此外,您似乎使用的是旧版本的 PHPMailer,并且您的代码基于旧示例。获取最新的here,并查看示例和 wiki。

【讨论】:

  • 感谢您给我的建议和解决方案 :) 我仍在尝试.. 另外,我已经使用了最新版本的 PHPMailer(我从您的链接中使用过)给我)。多亏了你,我已经在这里找到了真正的罪魁祸首 :) 还是谢谢。
【解决方案2】:

尝试在您的 PHPMailer 中使用此代码:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

【讨论】:

  • 抱歉,只是想澄清一下。该代码添加到我所有的 PHPMailer 类中? (也是'PHPMailerAutoload.php'?)或者你的意思是我发布的上面的代码? ||已编辑:我已经尝试过了,但仍然没有机会.. 感谢您的帮助:)
  • 删除前三行(从标题开始)并放上我上面提供的代码。
  • 对不起,我仍然遇到同样的错误,还有其他建议吗? :)
猜你喜欢
  • 2021-06-26
  • 2014-10-13
  • 2019-11-04
  • 2017-02-06
  • 2017-01-04
  • 2014-12-27
  • 2020-01-03
相关资源
最近更新 更多