PHP cURL问题:HTTP代码0

时间:2013-04-21 18:02:46

标签: php curl

我正试图通过cURL和PHP建立一个网站/ API。无论我尝试什么网址,我都会得到一个0的HTTP代码。我尝试过几个不同的网址。无论我尝试什么,我都会得到以下curl_getinfo(见下文)。我已经验证在PHP.ini文件中启用了cURL。

代码:

 // create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.yahoo.com");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

$report=curl_getinfo($ch);
print_r($report);

// grab URL and pass it to the browser
curl_exec($ch);

if(curl_errno($ch)) {
   echo 'Curl error: ' . curl_error($ch);
}

print curl_error($ch);

// close cURL resource, and free up system resources
curl_close($ch);

cURL_getinfo:

 Array
(
[url] => http://www.yahoo.com
[content_type] => 
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => 0
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0
[namelookup_time] => 0
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => -1
[upload_content_length] => -1
[starttransfer_time] => 0
[redirect_time] => 0
[certinfo] => Array
    (
    )

[primary_ip] => 
[primary_port] => 0
[local_ip] => 
[local_port] => 0
[redirect_url] => 
 )

1 个答案:

答案 0 :(得分:1)

您需要在curl_exec($ch);之前致电curl_getinfo($ch);,因为这是与服务器的实际连接:

旗帜CURLOPT_POST也没有必要,因为它是一个来电:

// create a new cURL resource
$ch = curl_init();

//for post calls:
//$post = 'a=b&d=c';
//$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=utf-8';
//$headers[] = 'Content-Length: ' . strlen($post);

//for get calls:
$headers = array();
$headers[] = 'Content-type: charset=utf-8'; 


$headers[] = 'Connection: Keep-Alive';

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.yahoo.com");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_exec($ch);
$report=curl_getinfo($ch);
print_r($report);

// grab URL and pass it to the browser


if(curl_errno($ch)) {
   echo 'Curl error: ' . curl_error($ch);
}

print curl_error($ch);

// close cURL resource, and free up system resources
curl_close($ch);