1

I'm about to build a small web service following the REST Architecture and I use the Slim Framework to handle Routing . I defined a post Route to be able to add a user for example in the database by sending the post request from another server using the curl Extension , the request is sent but I can't figure out a way to grab sent data to treat them in my callback function defined in the Routing . I let the code speak for itself : 1st , the route

$app->post('/users/create/', function ($data) use($app)
 {
   $app->response->status(201);
   echo "The user ".$data['name']." was added successfully";
 }
);  

then the post request sent using curl (from another page )

$data = array(
  'id' => 3,
  'name' => 'Gree3a'
);
$url = "http://localhost/api/users/create/";
$ic =  curl_init();

//set options
curl_setopt($ic, CURLOPT_URL, $url);
curl_setopt($ic, CURLOPT_POST, true);
curl_setopt($ic, CURLOPT_POSTFIELDS, $data);
curl_setopt($ic, CURLOPT_RETURNTRANSFER, true);

//perform our request
$result = curl_exec($ic);
curl_close($ic);

echo $result;

did I miss something ?

arakibi
  • 441
  • 7
  • 24

2 Answers2

0

You may have secured your route, if so, you have to put the following option:

curl_setopt($ch, CURLOPT_USERPWD, "user:password");
Mirza Selimovic
  • 1,669
  • 15
  • 18
0

OK I found it out , I changed the line :

curl_setopt($ic, CURLOPT_POSTFIELDS, $data);

TO :

curl_setopt($ic, CURLOPT_POSTFIELDS, http_build_query($data));

and then in the Route , I used $_POST['name'] and it worked .

arakibi
  • 441
  • 7
  • 24