Home > Software design >  Why is posting JSON with PHP Curl not working?
Why is posting JSON with PHP Curl not working?

Time:10-16

I have the following function:

function postCurl($url, $data){
    $data = json_encode($data);
    $ch = curl_init( $url);
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt( $ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

    $result = curl_exec( $ch );
    curl_close( $ch );
        
        return $result;
}

This function converts a (multidimensional) array to JSON should post it with curl.

The requested url simply returns all post values with:

echo '<pre>'.print_r(json_decode(file_get_contents("php://input")),1).'</pre>';

I verified with Postman that the requested url is working but when I post via curl I get no result. The only way I could replicate this issue with Postmanwas sending incorrect JSON so I bypassed the json_encode function and tried a valid JSON string but no result.

I got this function working in the past so I think it must be an issue with the settings.

Any help would be appreciated.

CodePudding user response:

I found the problem with help from this link:

file_get_contents('php://input') always returns an empty string

Because I used curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 ); I could not see that there was a redirect from www.url.com to url.com.

When a request is redirected you lose all data in file_get_contents("php://input")

  • Related