vespino
vespino

Reputation: 1940

translate curl to php

I'm looking for a way to perform this action using PHP:

curl -X POST <url> -H 'Authorization: AccessKey <key>' -d "recipients=xxx" -d "originator=yyy" -d "body=zzz"

This is what I came up with so far, but the only thing the api is responding is "false":

//headers
$headers=array(
    'Authorization: AccessKey key',
);

//postfields
$postfields=array(
    'originator'=>'yyy',
    'recipients'=>array('xxx'),
    'body'=>'zzz',
);

$ch=curl_init();

curl_setopt_array(
    $ch,
    array(
        CURLOPT_URL=>'url',
        CURLOPT_HEADER=>true,
        CURLOPT_HTTPHEADER=>$headers,
        CURLOPT_POST=>true,
        CURLOPT_POSTFIELDS=>$postfields,
        CURLOPT_RETURNTRANSFER=>true,
    )
);

$data=curl_exec($ch);

curl_close($ch);

var_dump($data);

Upvotes: 0

Views: 38

Answers (2)

echmel
echmel

Reputation: 154

try this (https://incarnate.github.io/curl-to-php/):

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "recipients=xxx&originator=yyy&body=zzz");

$headers = array();
$headers[] = 'Authorization: AccessKey <key>';
$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);

Upvotes: 1

doublesharp
doublesharp

Reputation: 27599

Your code looks correct so I would add some error logging to determine the cause of the non-response. You can use the curl_error() function to fetch the error when $data is false.

// fetch remote contents
if ( false === ( $data = curl_exec( $ch ) ) ) {
  // get the curl error
  $error = curl_error( $ch );
  var_dump( $error );                                           
}

Upvotes: 0

Related Questions