2

希望任何人都可以帮助我解决这个问题。我尝试使用 cURL 调用外部站点,但没有收到错误或响应。然而它在本地服务器上运行良好,但在生产服务器上不起作用。我已经使用 file_get_contents() 开始了通话,但在线也失败了。我与主机交谈,他们提到问题出在代码中。这是我的代码,任何人都可以帮忙!?

function send_with_curl($url, $data) {
   $data_string;
       //url-ify the data for the POST
    foreach ($data as $key => $value) { $data_string .= $key . '=' .  $value . '&';
}
rtrim($data_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

//execute post
$result = curl_exec($ch);
if (!is_string($result) || !strlen($result)) {      
    $result = "Failed to connect.";
}
//close connection
curl_close($ch);
return $result;
} 

我还有另一个使用 file_get_contents() 的函数,无论我使用哪个函数,它们都可以在本地工作,但在没有错误的情况下在线失败 我花了 4 多个小时试图与托管人员一起修复它,直到他们最终说错误在代码中,而他们没有不熟悉这些代码:(

function send_with_file($url, $context, $sender) {
global $database;
if (!$result = file_get_contents($url, false, $context)) {
    echo "Message sending failed, please check your internet.";
    exit ;
} else {
    //--UPDATING THE DATABASE------
    $sql_update = "SELECT * FROM users WHERE users_type='2'";
    $query_update = $database -> query($sql_update);
    while ($update = $database -> fetch_array($query_update)) {
        $update_user = $update['users_id'];
        if ($update_user == $sender) {

            if ($result === FALSE) {/* Handle error */
            }
        } else {

        }

    }
}
return $result;
}
4

2 回答 2

0

代码没有问题,我只是跟踪了我试图连接的 url,并意识到与托管服务器通信需要很长时间。

于 2016-05-11T20:16:24.827 回答
0

比较$result然后false检查curl_error()

就像是...

$result = curl_exec($ch);
if($result === false) {
    echo "Error in cURL : " . curl_error($ch);
}
于 2016-05-05T13:43:52.667 回答