PHP POST requests with curl

Jump to solution
Community Contributor

Hi fellow devs,

I'm just starting out with development in Canvas, and while I've done a lot with basic web dev stuff over the years, I've never tried to utilize APIs as heavily as I'm trying to now.

My main language is PHP for now, and I'm running into some trouble scripting a POST request to Canvas using curl. I have scripted GET requests without a problem. But when I try to run a POST request, I see a 403 error (Forbidden) in the response. It looks something like this:

string(1384) "HTTP/1.1 403 Forbidden

Cache-Control: no-cache

Content-Type: application/json; charset=utf-8

Date: Wed, 25 Nov 2015 15:00:52 GMT

etc, etc, etc.

X-UA-Compatible: IE=Edge,chrome=1

Content-Length: 33

Connection: keep-alive

{"message":"No parameters given"}"

The same request works from the command line via curl. I've read that PHP doesn't always insert a valid user-agent, and so I tried setting it with curl_setopt() dice.

Is there something else I'm missing here? Basically my code is:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $endpoint); // defined prior to this code

curl_setopt($ch, CURLOPT_HEADER, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_json); // fields array defined and prepped with json_encode() prior to this code

curl_setopt($ch, CURLOPT_HTTPHEADER, array(

    'Content-Type: application/json',

    'Content-Length: ' . strlen($fields_json),

    'Authorization: Bearer ' . $canvasCreds['apiKey']


$result = curl_exec($ch);


I've tinkered with adding other curl options, but nothing so far has worked. This is where my limited experience with curl is getting in my way...

Thanks in advance for any assistance.

-- Matt

Labels (1)
1 Solution
Community Contributor

OK, I have it now. My data was malformed - I just had to double-check the API documentation and I got it to work. Nothing specific to PHP curl. I was a bit thrown off that I got a 403 error for bad data, but thinking about it, I guess I can understand how that works.

View solution in original post