【问题标题】:Handling cURL in PHP在 PHP 中处理 cURL
【发布时间】:2017-10-13 01:50:29
【问题描述】:

我正在尝试将一个登录 Web 界面连接到我在 AWS 上已创建的身份验证活动存储库。我是新来的,我尝试过使用 Postman 来做这件事,它有一个用于 JSON 应用程序的原始模板,如下所示:

{
"userName" : "Victor",
"userPassword" : "pwd123"
}

它工作正常,我从我的存储库中收到了正确的答案。但是当我使用我的 php 项目来执行此操作时,我用完全相同的数据填写表单,我收到一条状态:403 消息:用户名或密码错误。

邮递员代码为我提供了 CURLOPT_POSTFIELDS 的解决方案:

CURLOPT_POSTFIELDS => "{\n\t\"userName\" : \"Victor\",\n\t\"userPassword\" : \"pwd123\"\n}",

但我需要用表单填写此字段,因此我将按照我将向您展示的方式更改它们。

这是我正在使用的代码,我真的卡住了,所以我会感谢任何帮助:)

public function loginAction(Request $request)
{
    $twigParams=array();
    $DTO = new LoginDTO($request, $this->container, null);
    $form = $DTO->getForm();
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {

        $upass = $DTO->getUserPass();
        $uname = $DTO->getUserName();

        $curl = curl_init();

        $fields=array("userName"=> $uname, "userPassword"=> $upass);
        curl_setopt_array($curl, array(
            CURLOPT_PORT => "80",
            CURLOPT_URL => "http://wt-services-internal-appl-blablabla..",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $fields ,
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application",
                ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

curl_close($curl);

$twigParams["form"]=$form->createView();
return $this->render('auth/login.html.twig', $twigParams);
}

【问题讨论】:

  • 现在已经解决了,我注意到在我的身份验证存储库中我有 JSON 格式的访问数据并且我没有以 JSON 格式发送数据,所以我做了什么来纠正那个是:$fields=array("userName"=> $uname, "userPassword"=> $uppass); $fields=json_encode($fields);我将该数组放在 CURLOPT_POSTFIELDS 中,并在 CURLOPT_HTTPHEADER 中将“content-type:application”更改为“content-type:application/json”。无论如何,谢谢,继续编码!
  • 将此评论写为答案并接受它。它将为您赢得一点声誉,并使其他开发人员也更容易看到答案。

标签: php symfony http curl postman


【解决方案1】:

我注意到在我的身份验证存储库中,我有 JSON 格式的访问数据,而我没有以 JSON 格式发送数据。为了解决这个问题,我这样做了:

$fields = array("userName" => $uname, "userPassword" => $upass);
$fields = json_encode($fields);

我将该数组放在CURLOPT_POSTFIELDS 中,并将CURLOPT_HTTPHEADER 中的“content-type: application”更改为“content-type: application/json”。

这样做解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多