使用curl发布请求 [英] post request using curl

查看:110
本文介绍了使用curl发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将按照REST体系结构构建一个小型Web服务,并且我将使用Slim Framework来处理Routing.我定义了一个发布路由,以便能够通过使用curl Extension从另一台服务器发送发布请求,从而在数据库中添加一个用户,该请求已发送,但我想不出一种方法来获取已发送数据以对其进行处理在路由中定义的回调函数中.我让代码说明一切: 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";
 }
);  

然后使用curl(从另一页)发送的发帖请求

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;

我错过了什么吗?

推荐答案

好,我发现了,我改变了这一行:

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));

然后在Route中,我使用$ _POST ['name']并成功了.

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

这篇关于使用curl发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆