Asked 8 years ago
19 Oct 2016
Views 13037
ching

ching posted

how to set custom HTTP header in CURL with php ?

how can i set custom HTTP header for curl php
i am working with api and i want to set HTTP request header with

User-Agent: PHP-SOAP-CURL


so i can send request with above HTTP header ?
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

it simple

$url='your web api url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,array(User-Agent: PHP-SOAP-CURL ) );
$response = curl_exec($ch);
curl_close($ch);	


curl_setopt($ch, CURLOPT_HTTPHEADER,array(User-Agent: PHP-SOAP-CURL ) );

curl_setopt use to sets an option(CURLOPT_HTTPHEADER) on the given cURL session handle($ch).


CURLOPT_HTTPHEADER is option for http header to be sent and you can pass array HTTP header fields to set in third argument

Rasi

Rasi
answered Nov 30 '-1 00:00

use CURL context

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded;User-Agent: PHP-SOAP-CURL'
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com', false, $context);

ravi

ravi
answered Nov 30 '-1 00:00



$host="127.0.0.1";
$ch = curl_init();
$headers = array(
 	'Connection: keep-alive',
	'User-Agent: PHP-SOAP-CURL',
	'Content-Type: application/json; charset=utf-8',
	'Accept: application/json',
	'Content-Length: ' . strlen($data_string),
	'Host '.$host);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);	
print_r($response);

you can add header field as many you need in array as above

http://php.net/manual/en/function.curl-setopt.php
Post Answer