-1

So i want to post this data

$data =  array(
  "exam_no"        => 'EX-A20210001',
  "uid"         => array('9a7f0d289c66ce63','c7f660212bb6d5cb'),
  "start_time"  => '2021-05-07 16:50:00',
  "end_time"    => '2021-05-07 17:30:00',
  "company_id"  => '14'
);

To this specific url : 'https://exam.nocortech.com/api/create-task

But i dont know how to ? Can someone help please ?

Question Maker
  • 151
  • 1
  • 1
  • 6

1 Answers1

0
<?php

$cr = curl_init("https://exam.nocortech.com/api/create-task"); # target URL
curl_setopt($cr, CURLOPT_POST, true); # use POST instead of default GET
$data =  array(
  "exam_no"     => 'EX-A20210001',
  "uid"         => array('9a7f0d289c66ce63','c7f660212bb6d5cb'),
  "start_time"  => '2021-05-07 16:50:00',
  "end_time"    => '2021-05-07 17:30:00',
  "company_id"  => '14'
);
curl_setopt($cr, CURLOPT_POSTFIELDS, json_encode($data)); # set post data and encode PHP object into JSON
curl_setopt($cr, CURLOPT_HTTPHEADER, array("Content-Type:application/json")); # key, set request Content-Type to application/json
curl_setopt($cr, CURLOPT_RETURNTRANSFER, true); # enabling allows return value through curl_exec
curl_setopt($cr, CURLOPT_FOLLOWLOCATION, true); # enabling allows to avoid a 307 temporarily redirect, I am not sure of the cause of the redirect
curl_exec($cr); # you get return value here
curl_close($cr);

?>

I hope this helps. I was working on PHP cURL too two days ago to link a website's backend with Gmail through Google App Script.

If anybody find any errors or mistakes in my solution, please point them out so that I can correct them.

L. Cang
  • 57
  • 6
  • Did you test this code? How did your `$data` turned to `$payload`? Also be careful when using `CURLOPT_RETURNTRANSFER`, according to documentation: `curl_exec` returns true on success or false on failure. However, if the `CURLOPT_RETURNTRANSFER` option is set, it will return the result on success, false on failure. – amrezzd May 10 '21 at 05:57
  • The OP, I assumed you want to use JSON as the format. I believe you can set the Content-Type to multipart/form-data as well. I believe PHP may default to multipart/form-data upon detecting $data is an array. – L. Cang May 10 '21 at 05:57
  • Hello Amir, I just edited the code. I saw the mistake. I have $payload in my code, but the OP has $data, so I went back and modified it. Also, I think the OP would like to receive the response from the other end, it could be another load of JSON information too. I am unsure of $CURLOPT_FOLLOWLOCATION, it could be a desperate fix to 307 redirect, but I am not sure whether it has security ramifications. – L. Cang May 10 '21 at 05:58
  • theres no error in the code, but the data cant update the database. Is it error from the code or from the API ? – Question Maker May 10 '21 at 06:05
  • Well, can you at least see whether the data arrives on the other end? – L. Cang May 10 '21 at 06:07