PHP Sending information by PUT [duplicate] - php

I am trying to create a HTTP PUT request with cURL and I can't make it work. I've read many tutorials but none of them actually worked. Here's my current code:
$filedata = array('metadata' => $rdfxml);
$ch = curl_init($url);
$header = "Content-Type: multipart/form-data; boundary='123456f'";
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($filedata));
$returned = curl_exec($ch);
if (curl_error($ch))
{
print curl_error($ch);
}
else
{
print 'ret: ' .$returned;
}
I've also tried using PHP PEAR but got the same result. The problem is that the repository says that no metadata has been set. I really need help! Thanks!

Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl

Using Postman for Chrome, selecting CODE you get this... And works
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://blablabla.com/comorl",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{\n \"customer\" : \"con\",\n \"customerID\" : \"5108\",\n \"customerEmail\" : \"jordi#correo.es\",\n \"Phone\" : \"34600000000\",\n \"Active\" : false,\n \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
"x-api-key: whateveriyouneedinyourheader"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>

In a POST method, you can put an array. However, in a PUT method, you should use http_build_query to build the params like this:
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );

You have mixed 2 standard.
The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";
The function http_build_query($filedata) is only for "Content-Type: application/x-www-form-urlencoded", or none.

Related

Send APi key and secret key in CURL

I'm trying to convert the line below to be used with PHP whilst also learning how to use CURL!
$ curl -X POST -d 'key=YOUR_KEY&secret=YOUR_SECRET' "https://api.example.co.uk/authenticate" -H "Content-Type: application/x-www-form-urlencoded"
Bellow is what I have so far, however I keep getting HTTP ERROR 403 UnauthorizedException accessing service error, so I think the key and secret and not being sent correctly.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.example.co.uk/authenticate",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"key\": \"MYKEY\",\"secret\": \"MYSECRET\"}",
CURLOPT_HTTPHEADER => array(
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Use this tool as it save so much time - https://incarnate.github.io/curl-to-php/
Generated this:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.co.uk/authenticate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "key=YOUR_KEY&secret=YOUR_SECRET");
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
Easy way is to use an array for header variable and assign api_key or secret key through array and pass that variable into curls->CURLOPT_HTTPHEADER
// Collection object
$ch = curl_init($url);
$headers = array(
"APIKEY: PUT_HERE_API_KEY",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml"
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlreq);
$result = curl_exec($ch); // execute
$result;
//show response
curl_close($ch);

CURLOPT_POSTFIELDS varaible format

I'm trying to post a parameter with cURL,
when I tried with this type of format :
CURLOPT_POSTFIELDS => "label=sample"
I exactly got "label" key in the server with "sample" as its value
but I get it empty in the server when I sent it out as a variable .
CURLOPT_POSTFIELDS => "label=$email"
$curl = curl_init();
$user_info=$this->web_model->retriveUserInfo();
$email=$user_info->email;
curl_setopt_array($curl, array(
CURLOPT_URL => "https://test.bitgo.com/api/v2/".$coin."/wallet/".$wallet_id."/address",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "label=$email",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Authorization: Bearer v2x4e7cf3fb7e6c2e87bf8103e49756b3892b2e350d6cdbaeb65757980",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Length: 11",
"Content-Type: application/x-www-form-urlencoded",
"Host: test.bitgo.com",
"Postman-Token: b3f2ee7c-9a19-479b-bfe2-27000c90e3c7,d611bde9-3eb1-4e2b-b8f5-a7a5f5485726",
"User-Agent: PostmanRuntime/7.15.2",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$response = json_decode($response, true);
$err = curl_error($curl);
curl_close($curl);
my main problem is CURLOPT_POSTFIELDS format for variables !
Doc says about CURLOPT_POSTFIELDS:
This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
So you can:
Replace: CURLOPT_POSTFIELDS => "label=$email", with CURLOPT_POSTFIELDS => ['label' => $email], and if you'll need more data to pass as POST field you can just add another pair $key => $value to that array or prepare it before setting curl options.
Set POST fields via http_build_query:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); where $ch is curl handle and $data is array of $key => $value pairs where $key is field name.
But keep in mind:
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
Many thanks
Finally I had to use Guzzle library simply
$client = new GuzzleHttp\Client(['base_uri' => 'https://test.bitgo.com/api/v2/']);
$response = $client->post($coin.'/wallet/'.$wallet_id.'/address', [
'headers' => [
'Authorization' => 'Bearer v2x4e7cf3fb7e6c2e87bf8103e4975dsddbaeb65ba017b555757980'],
'form_params' => [
"label" => $email
]
very very useful
You can try this
function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = false){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true);
}
if($json == true){
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$token, 'Content-Length: ' . strlen(json_encode($post))));
}else{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
// Proxy example only
if (!empty($proxy)) {
curl_setopt($ch, CURLOPT_PROXY, '127.0.0.1:888');
if (!empty($proxyAuth)) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'user:password');
}
}
if($ssl == false){
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->statusCode = $statusCode;
if (curl_error($ch)) {
$error = 'CURL_ERROR '.$statusCode.' - '.curl_error($ch);
// print_r('CURL_ERROR '.$statusCode.' - '.curl_error($ch));
throw new Exception('CURL_ERROR '.curl_error($ch), $statusCode);
}
curl_close($ch);
return $response;
}

I need to execute a curl request using php

Here is a query on the command line that works.
How can I get an answer to this request using PHP in the script?
curl -X GET https://megaservice.com/api/abonents -H 'X-AUTH-TOKEN: xxxxx-xxx-xxxxx' -H 'cache-control: no-cache'
This should work.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://megaservice.com/api/abonents",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"X-AUTH-TOKEN: xxxxx-xxx-xxxxx",
"cache-control: no-cache,no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
You can use cUrl:
$channel = curl_init('https://megaservice.com/api/abonents');
curl_setopt_array($channel, [
CURLOPT_RETURNTRANSFER => true, // Return curl-data to variable
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => [
'X-AUTH-TOKEN: xxxxx-xxx-xxxxx',
'cache-control: no-cache',
],
]);
$result = curl_exec($channel);
curl_close($channel); // Important thing - close channel for not load your server
var_dump($result); // Here's your result
You can post or get like this with curl,
function post($url, $data, $headerArray = ["Content-type:application/json;charset='utf-8'","Accept:application/json"])
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if ($headerArray){
curl_setopt($curl, CURLOPT_HTTPHEADER,$headerArray);
}
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
function get($url,$userpwd = "",$headerArray = ["Content-type:application/json;charset='utf-8'","Accept:application/json"]){
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if($userpwd) {
curl_setopt($curl, CURLOPT_USERPWD, $userpwd);
}
if($headerArray){
curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
}
$output = curl_exec($curl);
curl_close($curl);
return $output;
}

PHP request to API endpoint with authorized header

I would like to ask you how to use PHP request to API with authorized header.
API end point example is
Quotation Service : ­ POST https://api.website.com/v4/quotation
Content­type: application/json; charset=utf­8
Accept: application/json
Authorization: hmac $id:$milliSeconds:$signature
{
"serviceType": "CARD",
"specialRequests": [
"ROUNDTRIP"
]}
as you mention, they use hmac as an authorization in a header and request parameters is serviceType, specialRequest
I try using PHPCurl to make a request but i'm not a good on it. Please give me and advice how to use Curl with this API.
edit:
<?php
$customerId = "585a-SAMPLE-980dfe0097"; //by provider
$privKey = "MC4CAQACBQDSk4ghAgMB---SAMPLE---QIDAOPFAgMAk7QIDAMYq"; //by provider
$requestTime = (int)(microtime(true) * 1000);
$signature = hash_hmac('sha256', $requestTime, $privKey);
$headers = array(
"Authorization: hmac $customerId:$requestTime:$signature"
);
$params = array(
'serviceType' => 'CARD',
'specialRequests' => array('ROUNDTRIP')
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.samplesite.com/v1/quotations",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Regards,
Hmm ... maybe something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/v4/quotation');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
/* if you want to use SSL certificate, otherwise delete this */
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CAPATH , '/path/to/certificate');
$auth = hash_hmac('sha1', $id.':'.$milisecond.':'.$signature, <ENCRYPTION KEY>, true);
$headers = array(
'Authorization: '.$auth
);
$params = array(
'serviceType' => 'CARD',
'specialRequests' => array('ROUNDTRIP')
);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

PHP cURL HTTP PUT

I am trying to create a HTTP PUT request with cURL and I can't make it work. I've read many tutorials but none of them actually worked. Here's my current code:
$filedata = array('metadata' => $rdfxml);
$ch = curl_init($url);
$header = "Content-Type: multipart/form-data; boundary='123456f'";
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($filedata));
$returned = curl_exec($ch);
if (curl_error($ch))
{
print curl_error($ch);
}
else
{
print 'ret: ' .$returned;
}
I've also tried using PHP PEAR but got the same result. The problem is that the repository says that no metadata has been set. I really need help! Thanks!
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
Using Postman for Chrome, selecting CODE you get this... And works
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://blablabla.com/comorl",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{\n \"customer\" : \"con\",\n \"customerID\" : \"5108\",\n \"customerEmail\" : \"jordi#correo.es\",\n \"Phone\" : \"34600000000\",\n \"Active\" : false,\n \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/json",
"x-api-key: whateveriyouneedinyourheader"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
In a POST method, you can put an array. However, in a PUT method, you should use http_build_query to build the params like this:
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );
You have mixed 2 standard.
The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";
The function http_build_query($filedata) is only for "Content-Type: application/x-www-form-urlencoded", or none.

Categories