-1

I am in the process of trying to call a php script over http and receive a json object back from where I plan to process further.

Basically, the code is as follows:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $version=$_GET["v"];
        $product=$_GET["p"];
        $stream=$_GET["s"];
        $cmd=$_GET["c"];

        $string = file_get_contents("http://localhost:82/releasenote/src/getTSBDetails.php?p=$product&v=$version&s=$stream&c=$cmd");
        print_r($string);
        exit();
    } else {
        print("2");
        $string = file_get_contents('tsbDetails.json');
    }

When the get_file_contents http request is called directly in the browser, the output is a json, but when trying using the above there is no response.

Zulakis
  • 7,479
  • 10
  • 41
  • 62
user1270150
  • 53
  • 2
  • 7

2 Answers2

2

enter image description here

<?php
        // JSon request format is :
        // {"userName":"654321@zzzz.com","password":"12345","emailProvider":"zzzz"}

        // read JSon input
        $data_back = json_decode(file_get_contents('php://input'));

        // set json string to php variables
        $userName = $data_back->{"userName"};
        $password = $data_back->{"password"};
        $emailProvider = $data_back->{"emailProvider"};

        // create json response
        $responses = array();
        for ($i = 0; $i < 10; $i++) {
            $responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);
        }

        // JSon response format is :
        // [{"name":"eeee","email":"eee@zzzzz.com"},
        // {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]

        // set header as json![enter image description here][2]
        header("Content-type: application/json");

        // send response
        echo json_encode($responses);
        ?>


  [1]: http://i.stack.imgur.com/I7imt.jpg
  [2]: http://i.stack.imgur.com/XgvOT.jpg
Rush
  • 753
  • 4
  • 13
0

First of all you should make sure your variables can be used in the url:

    $version=urlencode($_GET["v"]);
    $product=urlencode($_GET["p"]);
    $stream=urlencode($_GET["s"]);
    $cmd=urlencode($_GET["c"]);

Then you should check if the value you read in $string is valid json. You can use this answer for that.

Then, if your string contains valid json, you should just echo it.

Finally, if you always expect json from your script, you should also json_encode your error handling:

} else {
    echo json_encode("2");
    // $string = file_get_contents('tsbDetails.json');  /* commented out as you don't seem to use it */
}
Community
  • 1
  • 1
jeroen
  • 90,003
  • 21
  • 112
  • 129