Moinul Hossain
Moinul Hossain

Reputation: 2206

php: curl script working but not in php file

I have a curl script that is working fine in terminal.

curl -XPOST \
     -F "file=@var/www/myfile.wav;type=audio/wav" \
     -H 'Authorization: Bearer $MY_TOKEN' \
     'https://myurl'

I have tried this way in my php file,

<?php

    $url = "https://myurl";
    $key =  "myKey";

    $path = "/var/www/";
    $fileName = "myfile.wav";
    $data['file']=  "@".$path.$fileName;
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER,array("Authorization: Bearer $key"));

    $response = curl_exec($ch);

    curl_close($ch);

    echo $response;

?>

I get an error from the server. Seems I am not making request as the server expects. Am I missing anything in the php script?

Upvotes: 1

Views: 715

Answers (2)

Tom Pace
Tom Pace

Reputation: 2387

Try this:

$data = array('file' => file_get_contents($path.$fileName));

There may be a problem with your CURL library that PHP is using.

Or PHP may be blocked from making HTTPS connections.

Try a series of simple tests using CURL in PHP like this first one with POST false:

<?php 

    $url = "https://myurl/";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    header("Content-Type: text/plain");
    echo $response;
?>

and then with POST true...

<?php 

    $url = "https://myurl/";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    header("Content-Type: text/plain");
    echo $response;
?>

Upvotes: 1

Since it's an HTTPs URL , You need to make use of this parameter

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

Upvotes: 0

Related Questions