file_get_contents('php://input') always returns an empty string

后端 未结 12 2251
遥遥无期
遥遥无期 2020-12-09 09:04

I\'m building a PHP RESTful API, following this tutorial. The following function, which should return the data sent with the request when the \'put\' method is used, returns

12条回答
  •  孤街浪徒
    2020-12-09 09:42

    First off, i was able to run this code and it worked fine:

    --Terminal---------
    //I ran this curl request against my own php file:
    curl -i -X PUT -d '{"address":"Sunset Boulevard"}' http://localhost/test.php
    
    
    --PHP--------------
    //get the data
    $json = file_get_contents("php://input");
    
    //convert the string of data to an array
    $data = json_decode($json, true);
    
    //output the array in the response of the curl request
    print_r($data);
    

    If that doesn't work, check the console for errors and your php settings:

    1. the curl url you used, make sure that url is actually working and not returning errors.
    2. open up another terminal / console window and run tail -f /path/to/the/php/log/file so you can actually see the output of these php calls.
    3. often people get this error: file_get_contents(file://input): failed to open stream: no suitable wrapper could be found which can indicate either a typo of the "file://input" string or the fact that allow_url_fopen is disabled in php (see #5 if unsure)
    4. make sure your code is correct, and by that I mean make sure you're not typing in incorrect arguments and things... stuff that doesn't necessarily get underlined in netbeans.
    5. remember, file_get_contents only works when allow_url_fopen is set to true in your PHP settings. thats something that is set in php.ini, but you can also change settings at run time by writing something along the lines of the following code before the other code:

      ini_set("allow_url_fopen", true);
      

提交回复
热议问题