2

我正在尝试通过 cURL 和 PHP 建立一个网站/API。无论我尝试什么 URL,我都会得到一个 0 的 HTTP 代码。我尝试了几个不同的 URL。无论我尝试什么,我都会返回以下 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] => 
 )
4

1 回答 1

1

您需要先调用curl_exec($ch);curl_getinfo($ch);因为这是与服务器的实际连接:

标志中也不需要,CURLOPT_POST因为它是一个 get 调用:

// 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);
于 2013-04-21T18:12:17.423 回答