Julian
Julian

Reputation: 1831

Connecting with a service via PHP cURL to send data not working

I'm trying to POST to the linksalpha API. I've tried countless ways but I don't even get a response from their servers when it comes to post.

Here is the dev page that I've setup. The content multipart response looks weird to me. The code I've written (api now hidden) is below. Nothing I try to do works :( :

<html>
<head></head>
<body>
<?php
$link = 'http://api.linksalpha.com/ext/post';

$data = array(
    'api_key' => 'xxxxxxxxxxxxxx',
    'post_id' => '434345',
    'post_link' => 'www.google.com',
    'post_title' => 'test title',
    'post_content' => 'test msg'
);

function networkpub_http_post($link, $body) {

    $url = $link;
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    $response = curl_exec($ch);

    function dbg_curl_data($ch, $data=null) {
      static $buffer = '';

      if ( is_null($ch) ) {
        $r = $buffer;
        $buffer = '';
        return $r;
      }
      else {
        $buffer .= $data;
        return strlen($data);
      }
    }

    echo '<fieldset><legend>request headers</legend>
      <pre>', htmlspecialchars(curl_getinfo($ch, CURLINFO_HEADER_OUT)), '</pre>
    </fieldset>';

    echo '<fieldset><legend>response</legend>
      <pre>', htmlspecialchars(dbg_curl_data(null)), '</pre>
    </fieldset>';



    curl_close($ch);

    return $response;

}


    $response_full = networkpub_http_post($link, $data);

    echo($response_full);
?>
</body>
</html>

Upvotes: 0

Views: 165

Answers (1)

GBD
GBD

Reputation: 15981

if you pass CURLOPT_POSTFIELDS with array then it will count as multipart/form-data but to post data through cURL then you need application/x-www-form-urlencoded version

So put following before your function start

$body = http_build_query($body);

Upvotes: 1

Related Questions