PHP Curl get and post example

Below are 3 functions for curl post , curl get and for check through curl if particular file is exists on remote server or not.

function curl_get($url, $params = array()) {
$ch = curl_init();

// set url

$param_str = "";
foreach($params as $key => $value) {
if($param_str == '') {
$param_str = $key . "=" . $value;
}else {
$param_str .= '&' . $key . "=" . $value;
}

}

$url = $url . "?" . $param_str;

curl_setopt($ch, CURLOPT_URL, $url);

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// $output contains the output string
$output = curl_exec($ch);

if(isset($params['debug'])) {
print $url;
die;
}
// close curl resource to free up system resources

curl_close($ch);

return $output;
}


How to use curl_get function.

$params = array();
$params['name'] = "John Doe";
$params['mobile'] = "1711523698";
$url = "http://www.example.com/registeruser.json";
$data = curl_get($url, $params);
$data = json_decode($data,true);
print_r($data);

function curl_post($url, $params = array()) {
$fields = array();
foreach($params as $key => $value) {
$fields[$key] = urldecode($value);
}

$fields_string = '';

//url-ify the data for the POST
foreach($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}

rtrim($fields_string, '&');

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);
$data = json_decode($result,true);
return $data;

}

How to use curl_post function.

$params = array();
$params['name'] = "John Doe";
$params['mobile'] = "1711523698";
$url = "http://www.example.com/registeruser.json";
$data = curl_post($url, $params);
$data = json_decode($data,true);
print_r($data);

Curl based function to check on remote server if file is exists or not.


function is_url_exist($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if($code == 200){
$status = true;
}else{
$status = false;
}
curl_close($ch);
return $status;
}

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

seven − 5 =