2017-07-26 20 views
0

我正在嘗試使用PHP和cURL獲取有關Cloudflare防火牆中特定IP的信息。cURL GET請求忽略我的數據輸入

但是,以下請求始終返回全部在防火牆中設置的IP。

對於GET請求,不可能使用CURLOPT_POSTFIELDS嗎?

如何正確地建立一個GET請求與PHP和cURL具有數據要求的數組?

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $this->settings['cloudflare_rules_url']); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); 

$headers = [ 
    'X-Auth-Email: ' . $this->settings['x_auth_email'], 
    'X-Auth-Key: ' . $this->settings['x_auth_key'], 
    'Content-Type: application/json', 
]; 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

$search_filter = array(
    'configuration_target' => 'ip', 
    'configuration_value' => '123.123.123.123', 

); 

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($search_filter)); 

$result = curl_exec($ch); 

curl_close($ch); 

error_log(print_r(json_decode($result, true), true)); 

回答

0

我找到了答案,但我不確定這是否是最優雅的方式。

解決方法是將查詢數組參數url編碼到CURLOPT_URL中。

$search_filter = array(
    'configuration_target' => 'ip', 
    'configuration_value' => '123.123.123.123', 

); 

curl_setopt($ch, CURLOPT_URL, $this->settings['cloudflare_rules_url'] . '/?' . http_build_query($search_filter)); 
+1

是您必須將數據添加到網址,如果方法GET – Matx132

+0

@ Matx132是不正確的。 GET請求可以具有請求體,就像POST請求一樣。它只是不常見的。爲了證明這一點,運行'curl -v -X GET --data test = foo example.org',看看,你會得到什麼?一個帶請求正文的GET請求,以及內容長度,就像POST請求:) – hanshenrik

+0

@hanshenrik爲什麼它在上面的示例中不起作用?是否因爲我使用PHP來構建請求? – alev