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

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_arrayDocs in PHP (all available options are explained at curl_setoptDocs):
$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);

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);
?>

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

Related

Need assistance with PHP curl call

Hello: I am trying to do an API call using curl_init; have made some good progress but seem to be stuck...
we have an interface (swagger) that allows us to do the curl call and test it which works: here is the curl commands from that:
curl -X POST --header "Content-Type: application/x-www-form-urlencoded"
--header "Accept: application/json"
--header "Authorization: Bearer xxxxx-xxxxxx- xxxxx-xxxxxxx"
-d "username=xxxxxxxx39%40gmail.com&password=xxxx1234" "http://xxxxxxxxx-xx-xx-201-115.compute-1.amazonaws.com:xxxx/api/users"
here is my attempt to do the same call in PHP code:
$json = '{
"username": "xmanxxxxxx%40gmail.com",
"password": "xxxx1234"
}';
$gtoken='xxxxxx-xxxxxx-xxx-xxxxxxxx';
$token_string="Authorization: Bearer ".$gtoken;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://exx-ccc-vvv-vvvv.compute-1.amazonaws.com:xxxx/api/users', //URL to the API
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
CURLOPT_HEADER => true, // Instead of the "-i" flag
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded','Accept: application/json',$token_string)
));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
$resp = curl_exec($curl);
curl_close($curl);
I am getting a response code "500" which makes me think that there is something wrong with my input. So I am wondering if anyone can help with this...
In your command line code, you post a standard URL encoded data string using -d "username=xxxxxxxx39%40gmail.com&password=xxxx1234" but in PHP you are creating a JSON string and sending it as a single post field (not properly URL encoded).
I think this is what you need:
$data = array(
'username' => 'xmanxxxxxx#gmail.com',
'password' => 'xxxx1234',
);
$data = http_build_query($data); // convert array to urlencoded string
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
As far as I can tell the rest of the code looks fine.
Also, you don't explicitly need to set the Content-Type header, cURL will do this for you when you pass a string to CURLOPT_POSTFIELDS. It will set it to multipart/form-data if you pass an array to CURLOPT_POSTFIELDS. But having it doesn't hurt anything either.

Create HTTP GET Header Request

I am using php and I want to create a HTTP request to access some API data. I have a document that says, I need to place the following request
GET /abc/api/Payment HTTP/1.1
Content-Type: application/x-www-form-urlencoded
X-PSK: [App Key]
X-Stamp: [UTC Timestamp]
X-Signature: [HMACSHA256 base 64 string]
Body:
var1, var1
I have app key, I can get UTC Timestamp and I can create signature. I am not sure how to start creating this request? I am using codeingiter. If someone can help with example to set the header and body?
I also tried this url https://www.hurl.it/ to place requests but can't make it work. Any suggestions?
You want to use cURL's CURLOPT_HTTPHEADER option.
http://php.net/manual/en/function.curl-setopt.php
This should get you started
function request($url) {
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"X-PSK: [App Key]",
"X-Stamp: [UTC Timestamp]",
"X-Signature: [HMACSHA256 base 64 string]"
),
CURLOPT_FOLLOWLOCATION => true
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) die(curl_error($ch));
curl_close($ch);
return $answer;
}

add headers to file_get_contents in php

I am completely new PHP and want a client program to call an URL web service.I am using file_get_content to get the data.How do add additional headers to the request made using file_get_content.
I also was thinking of using cURL. I wanted to know how cURL can be used to do a GET request.
You can add headers to file_get_contents, it takes a parameter called context that can be used for that:
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Host: www.example.com\r\n" .
"Cookie: foo=bar\r\n"
)
));
$data = file_get_contents("http://www.example.com/", false, $context);
As for cURL, the basic example from the PHP manual shows you how to perform a GET request:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>

Make HTTP/1.1 request with PHP

My code is using file_get_contents() to make GET requests to an API endpoint. It looks like it is using HTTP/1.0 and my sysadmin says I need to use HTTP/1.1. How can I make an HTTP/1.1 request? Do I need to use curl or is there a better/easier way?
Update
I decided to use cURL since I am using PHP 5.1.6. I ended up forcing HTTP/1.1 by doing this:
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
If I was using 5.3 or later I would have tried doing something like this:
$ctx = stream_context_create(array(
'http' => array('timeout' => 5, 'protocol_version' => 1.1)
));
$res = file_get_contents($url, 0, $ctx);
echo $res;
http://us.php.net/manual/en/context.http.php
Note: PHP prior to 5.3.0 does not
implement chunked transfer decoding.
If this value is set to 1.1 it is your
responsibility to be 1.1 compliant.
Another option I found which might provide HTTP/1.1 is to use the HTTP extension
I'd use cURL in either case, it gives you more control and in particular it gives you the timeout option. That's very important when calling an external API so as not to allow your application to freeze whenever a remote API is down.
Could like this:
# Connect to the Web API using cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.url.com/api.php?123=456');
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xmlstr = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
cURL will use HTTP/1.1 per default, unless you specify something else using curl_setopt($s,CURLOPT_HTTPHEADER,$headers);, where $headers is an array.
Just so others who want to use stream_context_create/file_get_contents know, if your server is configured to use keep-alive connections, the response will not return anything, you need to add 'protocol_version' => 1.1 as well as 'header' => 'Connection: close'. Example below:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 5,
'protocol_version' => 1.1,
'header' => 'Connection: close'
)
));
$res = file_get_contents($url, 0, $ctx);

Should I use file_get_contents or curl for web service requests?

I have a zip code lookup service and I'm worried about any possible timeouts or the server being down.
If I don't get any HTTP Response after 20-25s of the initial request I would want to respond with a JSON signifying it failed:
({ success:0 })
You can set timeout (and a lot of other options) for file_get_contents() as well using stream_context_create(). See here for a list of options.
Modified example from the manual:
<?php
$opts = array(
'http'=>array(
'timeout' => 25,
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$contents = file_get_contents("http://example.com", false, $context);
?>
If that works for you, I see nothing speaking against using cURL over this.
Your title and your question text pose two different questions. Both cURL and file_get_contents can use a timeout with a specific return.
If you use cURL, you can set the timeout using curl_setopt($ch, CURLOPT_TIMEOUT, 25) //for 25s.
To set the timeout for file_get_contents you have to include it in your context.
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>"25",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
Note however that file_get_contents, unlike cURL, has a default timeout (found in the option default_socket_timeout).
Both cURL and file_get_contents return FALSE on a failed transfer, so catching a failure is easy.
cURL has a lot more features and it'll probably be more useful in your case.
You can use this
curl_setopt($ch, CURLOPT_TIMEOUT, 40); //enter the number of seconds you want to wait

Categories