vovan
vovan

Reputation: 11

convert command curl to php

Hi all! I have curl command (audio file upload):

curl -k -v -H "Expect: " -H "Content-Type:application/octet-stream" --data-binary  '@/Path/To/File/test.wav' -X POST  'https://myapi.com?param1=xxx&param2=yyy'

File successfully uploaded and readable. But when I used php script:

$filename = 'test.wav';
$file = '@/Path/To/File/test.wav';

$post_url = "https://someapi.com?param1=xxx&param2=yyy";
$post_str = array("$filename" => $file);

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/octet-stream'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$http_body = curl_exec($ch);
var_dump($http_body);

File successfully uploaded and test.wav is not valid (with some error). What am I doing wrong in the script?

Upvotes: 1

Views: 748

Answers (2)

vovan
vovan

Reputation: 11

$filename = 'test.wav';
$file = '/Path/To/File/test.wav';

$post_url = "https://someapi.com?param1=xxx&param2=yyy";
$post_str = file_get_contents($file);
$headers = array('Content-Type:application/octet-stream', 'Expect: ');

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_VERBOSE,true); 
curl_setopt($ch, CURLOPT_STDERR, fopen("/Path/to/header.txt", "w+"));
$http_body = curl_exec($ch);

It's work perfect. I solved the problem myself. File upload to the server binary. Thank you all!

Upvotes: 0

Jim
Jim

Reputation: 22656

I suspect the issue is these lines:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/octet-stream'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));

The second call will remove the "Content-Type" Header. Try consolidating these:

$headers = array('Content-Type:application/octet-stream','Expect: ');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Upvotes: 3

Related Questions