Cannot read file_get_contents

Hi all,
I’m attempting to write a simple api to accept some post data, but I can’t seem to read anything using the
[php]
file_get_contents(‘php://input’)
[/php]
method…

I have spent a lot of time browsing other peoples issues on SE and in various areas and haven’t been able to figure it out.

My whole script is simply:
[php]

<?php header('content-type: application/json; charset=utf-8'); ini_set("allow_url_fopen", true); ini_set("request_order", "GP"); $post = file_get_contents('php://input'); echo json_encode([ "hardcoded" => "response", "content_type" => $_SERVER['CONTENT_TYPE'], "request" => $post ]); ?>

[/php]

and I test this via ajax with the following:

jQuery.ajax({
    "type": "POST",
    "url": "https://www.myaddress.com/api/1/bug/filesubmit",
    "data": {
        "foo": "bar"
    }
}).done(function (d) {
    console.log(d);
});

and I get back:

{hardcoded: "response", content_type: "application/x-www-form-urlencoded; charset=UTF-8", request: ""}

Some solutions I’ve tried had me set the htaccess file with the following:

######################
## Handling Options for the CORS
     RewriteCond %{REQUEST_METHOD} OPTIONS
     RewriteRule ^(.*)$ $1 [L,R=204]

###################
## Add custom headers

    Header set X-Content-Type-Options "nosniff"
    Header set X-XSS-Protection "1; mode=block"
       # Always set these headers for CORS.
    Header always set Access-Control-Max-Age 1728000
    Header always set Access-Control-Allow-Origin: "*"
    Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
    Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,C$
    Header always set Access-Control-Allow-Credentials true

I’m at a loss… I don’t know what else to do to read post data. Seems like this should be a lit easier than it is. In addition: why is it that the content type is “application/x-www-form-urlencoded; charset=UTF-8”?

[php]

print_r($_POST);

[/php]

still nothing…

[php]

<?php header('content-type: application/json; charset=utf-8'); ini_set("allow_url_fopen", true); ini_set("request_order", "GP"); $post = file_get_contents('php://input'); print_r($_POST); echo json_encode([ "hardcoded" => "response", "content_type" => $_SERVER['CONTENT_TYPE'], "request" => $post ]); ?>

[/php]

Array
(
)
{"hardcoded":"response","content_type":null,"request":""}

Doing an ajax post request will show the request in post. It isn’t json content though. Comment everything out, but the print_r statement.

Thanks. I tried that now:

I get the same result:

Array
(
)

Since you are trying to create an API?

Look into this rather than trying to roll your own for now.
https://www.slimframework.com/

Sponsor our Newsletter | Privacy Policy | Terms of Service