How to write curl -X PUT -T script in php - php

I am working on a Hootsuite script that needs to upload a file using cURL PUT request. On Hootsuite site, I found below example code but I am being able to convert below code in PHP script :
curl -X PUT -H 'Content-Type: video/mp4' \
-H "Content-Length: 8036821" \
-T "/Users/kenh/Downloads/amazing_race.mp4" \
"https://hootsuite-video.s3.amazonaws.com/production/3563111_6923ef29-d2bd-4b2a-a6d2-11295411c988.mp4?AWSAccessKeyId=AKIAIHSDDN2I7V2FDJGA&Expires=1465846288&Signature=3xLFijSn02YIx6AOOjmri5Djkko%3D"
I tried below code but it is still not working :
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://hootsuite-video.s3.amazonaws.com/production/3563111_6923ef29-d2bd-4b2a-a6d2-11295411c988.mp4?AWSAccessKeyId=AKIAIHSDDN2I7V2FDJGA&Expires=1465846288&Signature=3xLFijSn02YIx6AOOjmri5Djkko%3D",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => array('file' => '#' . realpath('/Users/kenh/Downloads/amazing_race.mp4')),
CURLOPT_HTTPHEADER => array(
'Content-Type: video/mp4',
'Content-Length: 8036821'
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
So can anybody help me out by telling how to convert above code in PHP ?
I'll be thankful.

Try appending http_build_query on the CURLOPT_POSTFIELDS option, like below :
CURLOPT_POSTFIELDS => http_build_query( array( 'file' => '#' . realpath( '/Users/kenh/Downloads/amazing_race.mp4' ) ) ),
From what I know, the http_build_query is required on the post fields when using PUT method.

Related

How to properly uploads files to certain api uisng curl in php

Am trying to add/upload files to monday.com api via curl in php but the code throws error {"error_message":"Internal server error","status_code":500}
Monday Docs
here is the API Curl request
curl --location --request POST 'https://api.monday.com/v2/file' \
--header 'Authorization: YourSuperSecretAPIKey' \
--form 'query="mutation add_file($file: File!, $item_id: Int!, $column_id: String!) {add_file_to_column (item_id: $item_id, column_id: $column_id, file: $file) {id}}"' \
--form 'variables="{\"item_id\":1104589438, \"column_id\": \"files\"}"' \
--form 'map="{\"image\":\"variables.file\"}"' \
--form 'image=#"/Users/alexsavchuk/Downloads/300px-All_Right_Then,_Keep_Your_Secrets.jpg"'
Arguments Description of the API Variable
item_id !Int The item ID where the file will be added.
column_id !String The column where the file will be added.
file !File The file to upload.
Here is my coding efforts
$token = 'Token goes here';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.monday.com/v2/file',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('query' => 'mutation ($file: File!) { add_file_to_column(file: $file, item_id: 279111, column_id: "files") { id } }','variables[file]'=> new CURLFILE('https://cdn.pixabay.com/photo/2015/05/26/12/30/baby-784608_960_720.jpg')),
CURLOPT_HTTPHEADER => array('Authorization: ' . $token)));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

How to translate curl arguments to php-curl?

(i've seen SOME version of this question so many times, hoping to make a thread with a comprihensive-ish list of answers)
for example, what is the php-curl translation of:
curl -v https://api-m.sandbox.paypal.com/v1/oauth2/token \
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
-u "client_id:secret" \
-d "grant_type=client_credentials"
-v translates to
curl_setopt($ch,CURLOPT_VERBOSE, 1);
PS! by default, curl sends this data to stderr, and stderr is usually visible when running curl from the terminal, but when running php-curl behind a webserver ala nginx/apache, it's not uncommon that stderr is linked to *the web-server's errorlog*, hence the VERBOSE log may arrive in the server error log, rather than the browser. a quickfix to this would be to set a custom CURLOPT_STDERR, ala:
$php_output_handle = fopen("php://output", "wb");
curl_setopt_array($ch, array(
CURLOPT_VERBOSE => 1,
CURLOPT_STDERR => $php_output_handle
));
but because of php garbage collection, when using this quickfix, keep in mind that it will break if php garabge collector closes $php_output_handle before the last curl_exec() call to the same handle.. it's usually not a problem, but it can happen.
.. moving on,
https://api-m.sandbox.paypal.com/v1/oauth2/token translates to:
curl_setopt($ch,CURLOPT_URL, 'https://api-m.sandbox.paypal.com/v1/oauth2/token');
and
-H "Accept: application/json" \
-H "Accept-Language: en_US" \
translates to
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: application/json",
"Accept-Language: en_US"
));
and -u "client_id:secret" translates to:
curl_setopt($ch,CURLOPT_USERPWD, "client_id:secret");
and -d "grant_type=client_credentials" (aka --data) translates to:
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query(array(
"grant_type" => "client_credentials"
))
));
hence the full translation is:
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_VERBOSE => 1,
CURLOPT_URL => 'https://api-m.sandbox.paypal.com/v1/oauth2/token',
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Accept-Language: en_US"
),
CURLOPT_USERPWD => 'client_id:secret',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query(array(
"grant_type" => "client_credentials"
))
));
curl_exec($ch);
what is the translation of curl -F grant_type=client_credentials ?
it's:
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
"grant_type" => "client_credentials"
)
));
what about uploading files, what's the translation of curl -F file=#file/path/to/upload.ext ?
it's:
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
"file" => new CURLFile("filepath/to/upload.ext")
)
));
what's the translation of --location ? it's
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
how to upload JSON? like this:
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json"
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode(array(
"whatever_key" => "whatever_data"
))
));
-X PUT translates to
curl_setopt($ch,CURLOPT_PUT,1);
as for --upload-file , there are several ways to do it,
if you're dealing with small files which easily fits in ram, the easiest way to do it would be:
curl_setopt_array($ch, array(
CURLOPT_PUT => 1,
CURLOPT_POSTFIELDS => file_get_contents($file)
));
but if you need to support big files which you don't want to put in RAM,
$file = "file.ext";
$file_handle = fopen($file,"rb");
$file_size = filesize($file);
curl_setopt_array($ch, array(
CURLOPT_UPLOAD => 1,
CURLOPT_INFILESIZE=>$file_size,
CURLOPT_INFILE=>$file_handle
));

PHP Get Access an Token from Gotowebinar API

I try using PHP to get an access token in GoToWebinar API, from this documentation https://developer.goto.com/guides/HowTos/03_HOW_accessToken/
here my php script
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.getgo.com/oauth/v2/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
'Authorization: Basic MWM4ODE2MmItMGZkZS00YTM4LWI0NGMtMWMzOGFhMDY5YmI4OktQSDg2d1hnVUM5a0FqbithMVBsOGc9PQ==',
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
),
CURLOPT_POSTFIELDS =>"redirect_uri=http://indotourismevents.com/webinar&grant_type=authorization_code&code=eyJraWQiOiJvYXV0aHYyLmxtaS5jb20uMDIxOSIsImFsZyI6IlJTNTEyIn0.eyJscyI6IjczYjkyNzhmLTBmNjMtNDE3NC1iYTljLWE3ZTIyYzIwMDhmNyIsInVyaSI6Imh0dHA6Ly9pbmRvdG91cmlzbWV2ZW50cy5jb20vd2ViaW5hci8iLCJzYyI6ImNvbGxhYjogaWRlbnRpdHk6c2NpbS5tZSBpZGVudGl0eToiLCJhdWQiOiIxYzg4MTYyYi0wZmRlLTRhMzgtYjQ0Yy0xYzM4YWEwNjliYjgiLCJzdWIiOiIzODc4MTIxOTUzODYzNTgxMTkwIiwianRpIjoiOTgyYTYyMWQtYTFhYi00NTE3LWFlYTgtNDFlYmY3OWE0NzFlIiwiZXhwIjoxNTk0NzQxOTUxLCJpYXQiOjE1OTQ3NDEzNTEsInR5cCI6ImMifQ.Cy6TR18iKmCtotZnnPvMUS9QMh4EFBP6FMcqBOWN9LtricreNg1qnA45UJB0cQALB1d5h9zgc-nDkU4GtTNr8ZnDSI26On3YqFJBICptmfrHhI7ZZIwH-p8YilKirHua1shEPVpradyAj_epjfmejd35QbCXD8aTz3uq-ocRGZFvz0WZfAA7wWryMBnkvTm5BM4fTx99Q4AGfT27QFomaR4hGsLy6uUM4N3rcqP7VNM21XeuIZ-5U1zd2Ew0-gnWoNo8lOF1hJeihZ_xyMlY9AgN7HAwW55JmUkFSsNVHdLznYebzXuDJZXGYnXxQwIyVym3tmx88JRUcI0bMzJ5-w",
));
$response = curl_exec($curl);
$err = curl_error($curl);
from the documentation, curl must give some header and form body
curl -X POST "https://api.getgo.com/oauth/v2/token" \
-H "Authorization: Basic YTIwfAKeNGYtODY4YS00MzM5LTkzNGYtNGRhMmQ3ODhkMGFhOjNuYU8xMElBMmFnY3ZHKzlJOVRHRVE9PQ==" \
-H "Accept:application/json" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "redirect_uri=https://example.com&grant_type=authorization_code&code=iS0vynEEvRFA9i6kZ8gvNDnnOGE..."
and i give all required header&form body, but still return an error like this
{"error":"invalid_request","error_description":"Required parameter(s) missing or wrong."}
how to PHP get access token from GoToWebinar API?
I experienced this problem when I logged in with the same user account to G2Webinar as my developer user (the oauth client's user was the same as the user webinar user)
Try to register another account.

PHP CURL does not return the full token

I am using PHP curl to do basic Auth that return a jwt token.
When I Request the token in shell using curl i get a token of length 381 .However when I do the request in my php code i only get a token of length 326 which is not complete which lead to other problems in my other php requests .
how can i make my php code give me the full length of my token that is 381 in my response and not just 326?
Update my cURL shell code is :
curl --location --request POST 'https://xxxx/xxxx/auth/login' \
--header 'Authorization: Basic XXXXX'
my curl php code :
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://xxxxx/xxxxx/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array( "Authorization: Basic xxxxxxx" ),
) );
$response = curl_exec($curl);
curl_close($curl); echo $response;
Thanks

Sending a POST with PHP doesn't work with curl or file_get_contents, just normal bash CURL

I'm having some serious problems sending a POST. Using curl on the shell, my POST works perfectly. However, when using PHP curl, or file_get_contents, it doesn't work at all. I get a 500 error from the webserver.
curl -X POST -H"Content-Type:application/xml" "http://myserver:8080/createItem?name=NewItem" --user root:123456 --data-binary #template.xml
And this:
$options = array(
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array("Content-Type:application/xml"),
CURLOPT_URL => "http://myserver:8080/createItem?name=" . rawurlencode("NewItem"),
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 20,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => "root:123456",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents("template.xml"),
);
$post = curl_init();
curl_setopt_array($post, $options);
if(!$result = curl_exec($post)) {
trigger_error(curl_error($post));
}
curl_close($post);
And this:
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => sprintf("Authorization: Basic %s\r\n", base64_encode('root:123456')) . "Content-Type:application/xml",
'timeout' => 20,
'content' => file_get_contents("template.xml"),
),
));
$ret = file_get_contents("http://myserver:8080/createItem?name=" . rawurlencode("NewItem"), false, $context);
Am i doing something absurd here and i'm not seeing? I don't see a reason for the normal curl from the shell to work perfectly, but not the PHP implementations.
Hum... I don't think that's possible with php/curl, but try:
CURLOPT_POSTFIELDS => array('#template.xml'),
It IS possible, take a look at this:
// same as <input type="file" name="file_box">
$post = array(
"file_box"=>"#/path/to/myfile.jpg",
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
Source: http://dtbaker.com.au/random-bits/uploading-a-file-using-curl-in-php.html
According to the documentation, headers here
'header' => sprintf("Authorization: Basic %s\r\n", base64_encode('root:123456'))
. "Content-Type:application/xml",
should end with \r\n [see example 1 here]
'header' => sprintf( "Authorization: Basic %s\r\n", base64_encode('root:123456'))
. "Content-Type: application/xml\r\n",

Categories