0

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.

I'm calling the api using file_get_contents. The apiURL is localhost/api/v1/login.

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

$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. If I do a var_dump($apiResponse) in login.php I get NULL as the value returned from the API.

Any thoughts on why this value is NULL? Am I calling the api endpoint incorrectly?

Ismail RBOUH
  • 10,292
  • 2
  • 24
  • 36
Runicode
  • 291
  • 2
  • 3
  • 19
  • Try to use `application/x-www-form-urlencoded` instead of `application/json` and don't forget to replace `"content" => json_encode($data)` with `"content" => http_build_query($data)` – Ismail RBOUH Jun 26 '16 at 04:24
  • Thanks for the feedback. I figured out the issue. I did not realize json_decode does not convert the JSON to an array automatically until you tell it to by setting the second arg to true. I was operating against the apiResponse as an associative array. Once I set it to true it fixed the issue. – Runicode Jun 27 '16 at 00:12

1 Answers1

0
$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

Community
  • 1
  • 1
Rupesh Bhandari
  • 76
  • 1
  • 12