如何将cURL转换为PHP cURL

时间:2019-03-20 19:29:24

标签: php curl

我正在使用API​​来验证一些数据,并且可以从命令行像下面这样获取其cURL API:

curl --get --include 'https://domainnameher.com/?domain=whatever@virtual-email.com' \
-H 'X-Mashape-Key: f123456879' \
-H 'Accept: application/json'

返回一些JSON-很好。当我尝试将其转换为PHP并作为表单处理器脚本运行时,服务没有返回任何内容。

HTML

<form id="testF" action="processor.php" method="POST">
    <input type="text" name="Email" id="Email" placeholder="Your Email Address">
    <input type="submit" class="redFlat" value="DOWNLOAD">
</form>

jQuery for AJAX

$(function(){
    $('#testF').validate({
        errorPlacement: function(error, element) {},
        submitHandler: function(form) {
            var dataString = $(form).serialize(); 
            $.ajax({
                type:$('#testF').attr('method'),
                url: form.action,
                data: dataString,
                dataType: 'json',
                success: function(data) {
                    console.log(data);
                }
            });
            return false;
        }
    });
});

主要问题-PHP处理器。我正在从表单中获取POST值,并将其附加到URL ...

<?php
    $email  = filter_var($_POST["Email"], FILTER_SANITIZE_EMAIL);
    $fields = array('domain' => $email);
    $url = "https://mailcheck.p.mashape.com/?" . http_build_query($fields, '', "&");
    $endpoint = urldecode($url);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $endpoint);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $headers = [
        'X-Mashape-Key: f123456879',
        'Accept: application/json'
    ];

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $server_output = curl_exec ($ch);

    curl_close ($ch);

    echo $server_output;
?>

我不知道为什么从终端运行命令时没有从脚本中得到相同的响应。任何建议都非常感谢。

1 个答案:

答案 0 :(得分:2)

除了CURLOPT_POST的明显错字以外,尼特夫妇还可以选择您的代码。您使用filter_var,但如果过滤器失败则继续执行;您应该检查错误的值。您不应该在URL上使用urldecodehttp_build_query的整个想法是它为您执行URL编码。这是个人喜好,但我发现curl_setopt_array的使用更容易。并且,应该在将结果发送回jQuery时检查结果是否为有效的JSON并使用正确的标头。

header("Content-Type: application/json");
$email  = filter_var($_POST["Email"], FILTER_SANITIZE_EMAIL);
if (!$email) {
    header("HTTP/1.1 500 Server Error");
    $res = ["result"=>false, "message"=>"Invalid email"];
    echo json_encode($res);
    exit;
}
$fields = ['domain' => $email];
$url = "https://mailcheck.p.mashape.com/?" . http_build_query($fields);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'X-Mashape-Key: f123456879',
        'Accept: application/json'
    ]
]);
$server_output = curl_exec($ch);

curl_close ($ch);

if (json_decode($server_output)) {
    echo $server_output;
} else {
    header("HTTP/1.1 500 Server Error");
    $res = ["result"=>false, "message"=>"Invalid response from server: $server_output"];
    echo json_encode($res);
}