简体   繁体   English

通过file_get_contents调用的故障调试PHP REST API

[英]Trouble Debugging PHP REST API called by file_get_contents

I'm working on login authentication and having trouble identifying the failure. 我正在进行登录身份验证,无法识别失败。 Via AJAX I pass the username and password to login.php which calls a PHP REST API to verify credentials and respond with a JSON containing the account status and a message that gets pushed back up to the UI. 通过AJAX,我将用户名和密码传递给login.php,后者将调用PHP REST API来验证凭据,并使用JSON进行响应,该JSON包含帐户状态和一条消息,并被推送回UI。

I'm calling the api using file_get_contents . 我正在使用file_get_contents调用api。 The apiURL is localhost/api/v1/login. apiURL是localhost / api / v1 / login。

login.php login.php

$data = array('username' => $username, 'password' => $password);
    $options = ["http" =>
        ["method" => "POST",
            "header" => "Content-Type: application/json",
            "content" => json_encode($data)
            ]
        ];

    // Call API
    $apiResponse = json_decode(file_get_contents($apiUrl, NULL, stream_context_create($options)));

The problem seems to be my api call, but I cannot figure out what the issue is. 问题似乎是我的api调用,但是我无法弄清楚问题是什么。

API API

$response = array("status" => "active", "message" => "success");

            header('Content-Type: application/json');
            echo json_encode($response);

I test my API using the postman chrome extension and send and receive JSON without issue so the API code is working. 我使用邮递员chrome扩展程序测试了我的API,并且没有问题地发送和接收JSON,因此API代码可以正常工作。 If I do a var_dump($apiResponse) in login.php I get NULL as the value returned from the API. 如果我在login.php中执行var_dump($apiResponse)var_dump($apiResponse)得到NULL作为从API返回的值。

Any thoughts on why this value is NULL? 关于为什么该值为NULL的任何想法? Am I calling the api endpoint incorrectly? 我是否错误地调用了api端点?

$data = http_build_query(
    array('username' => $username, 'password' => $password)
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $data
    )
);

$apiResponse = json_decode(file_get_contents($apiUrl, false, stream_context_create($opts)));

This might help you though I haven't tested the code 尽管我尚未测试代码,但这可能对您有帮助

ref: php , stackoverflow 参考: phpstackoverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM