简体   繁体   中英

How do I translate this command line curl into php curl?

I've got a command line curl bit of code that I want to translate into php. I'm struggling.

Here's the line of code

$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member

the big string would be a variable I'd pass into it.

What does this look like in PHP?

You first need to analyze what that line does:

$ curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member

It's not complex, you find all switches explained on curl's manpage :

-H, --header <header> : (HTTP) Extra header to use when getting a web page. You may specify any number of extra headers. [...]

You can add a header via curl_setopt_array Docs in PHP (all available options are explained at curl_setopt Docs ):

$ch = curl_init('https://api.service.com/member');
// set URL and other appropriate options
$options = array(        
    CURLOPT_HEADER => false,
    CURLOPT_HTTPHEADER => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
);
curl_setopt_array($ch, $options);
curl_exec($ch); // grab URL and pass it to the browser
curl_close($ch);

In case curl is blocked, you can do that as well with PHP's HTTP capabilities which works even if curl is not available (and it takes curl if curl is available internally):

$options = array('http' => array(
    'header' => array("Authorization: 622cee5f8c99c81e87614e9efc63eddb"),
));
$context = stream_context_create($options);
$result = file_get_contents('https://api.service.com/member', 0, $context);

You should look into the curl_* functions in php. With curl_setopt() you can set the headers of the request.

1) you can use Curl functions

2) you can use exec()

exec('curl -H "Authorization: 622cee5f8c99c81e87614e9efc63eddb" https://api.service.com/member');

3) you can use file_get_contents() if you only want the information as string...

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Authorization: 622cee5f8c99c81e87614e9efc63eddb"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.service.com/member', false, $context);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM