2016-04-29 144 views
2

PHP的curl令人驚訝地是不可取消和模糊的。使用cURL下載JSON API數據時遇到了一些問題。我想看看究竟發送到遠程HTTP服務器的是cURL。獲取PHP curl發送的數據

目前我唯一的調試選項是暫時發送請求到一些簡單的HTTP服務器,將輸入寫入標準輸出。我需要編寫這個服務器來調試curl!

我做什麼:

function get_data($url) { 
    $ch = curl_init(); 
    echo "Download: $url.\n"; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    // I hoped to get some debug info 
    // but this setting has no effect 
    curl_setopt($ch, CURLOPT_VERBOSE, true);  
    curl_setopt($ch, CURLOPT_HEADER, array(
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0', 
    'X-Purpose: Counting downloads.' 
)); 

    echo "Sending: \n".curl_getinfo($ch, CURLINFO_HEADER_OUT); 
    $data = curl_exec($ch); 

    var_dump($data); 
    echo curl_error($ch)." ".curl_errno($ch); 
    curl_close($ch); 
    return $data; 
} 

我怎樣才能獲得由捲曲發來的文本數據?

回答

0

如果要定義頁眉,你應該使用CURLOPT_HTTPHEADERCURLOPT_HEADER,即:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0', 
    'X-Purpose: Counting downloads.' 
)); 

要獲得內容捲曲發送使用:

curl_setopt($handle, CURLOPT_VERBOSE, true); 
curl_setopt($handle, CURLOPT_STDERR,$f = fopen($verbosePath, "w+")); 

function get_data($url) { 
$verbosePath = __DIR__.DIRECTORY_SEPARATOR.'verbose.txt'; 
echo "Saving verbose to: $verbosePath\n"; 
$handle=curl_init('http://www.google.com/'); 
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); 
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($handle, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0', 
    'X-Purpose: Counting downloads.' 
)); 
curl_setopt($handle, CURLOPT_VERBOSE, true); 
curl_setopt($handle, CURLOPT_STDERR,$f = fopen($verbosePath, "w+")); 
$data = curl_exec($handle); 
curl_close($handle); 
fclose($f); 
return $data; 
} 

get_data("https://www.google.com"); 

verbose.txt

* About to connect() to www.google.com port 80 
* Trying 172.217.0.100... * connected 
* Connected to www.google.com (172.217.0.100) port 80 
> GET/HTTP/1.1 
Host: www.google.com 
Accept: */* 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0 
X-Purpose: Counting downloads.