Justin's Words

PHP cURL GET & POST

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
function curlCrawler($url, $data=array(), $method='GET', $http_header = "application/x-www-form-urlencoded; charset=utf-8") {
$fields_string = '';
foreach ($data as $key => $value) {
$fields_string .= $key. '=' . $value . '&';
}

$curl_obj = curl_init();
curl_setopt($curl_obj, CURLOPT_HEADER, 0);

if (strtoupper($method) === 'POST') {
curl_setopt($curl_obj, CURLOPT_URL, $url);
curl_setopt($curl_obj, CURLOPT_POST, 1);
curl_setopt($curl_obj, CURLOPT_POSTFIELDS, $fields_string);
} elseif (strtoupper($method) === 'GET') {
curl_setopt($curl_obj, CURLOPT_URL, $url . '?'. $fields_string);
}

curl_setopt($curl_obj, CURLOPT_HTTPHEADER, array($http_header, "Content-Length: " . strlen($fields_string)));
curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_obj, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($curl_obj, CURLOPT_TIMEOUT, 20);

$rtn = curl_exec($curl_obj);

if (!curl_errno($curl_obj)) {
$response = $rtn;
} else {
$response = 'Curl error: ' . curl_error($curl_obj);
}

curl_close($curl_obj);
return $response;
}