post request using curl

穿精又带淫゛_ 提交于 2019-12-11 11:45:57

问题


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 ?


回答1:


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

curl_setopt($ch, CURLOPT_USERPWD, "user:password");



回答2:


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 .



来源:https://stackoverflow.com/questions/27542175/post-request-using-curl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!