简体   繁体   English

Laravel | PHP | 如何使用file_get_contents?

[英]Laravel | PHP | How to use file_get_contents?

I want to learn and to understand how can i use data, sent from an external server into my laravel project. 我想学习并了解如何使用从外部服务器发送到laravel项目的数据。

So i made this route : 所以我走了这条路:

Route::get('/receive','MyController@Receive');

And in Controller i did that : 在控制器中,我做到了:

 public function Receive(Request $request){
     $data = file_get_contents("php://input");
     $json_dat = json_decode($data, true);
     echo $json_dat;
 }

Using POSTMAN, i sent i POST request to ` http://my_domain/receive 使用POSTMAN,我将POST请求发送到` http:// my_domain / receive

With Body > Row > JSON APP And a simple table like that : ` 使用“正文”>“行”>“ JSON APP”和一个简单的表格:

[{
    "type_3": "Hero",
 }]

When executing the URL in Postman, nothing happens in echo $json_dat 在Postman中执行URL时,echo $json_dat没有任何$json_dat

What I'm expecting is : Json data with type_3 : Hero 我期望的是:带有type_3的Json数据:英雄

Thank you in advance 先感谢您

邮递员行动

Very simple, you're expecting a GET request rather than POST. 很简单,您期望的是GET请求而不是POST。

change 更改

Route::get('/receive','MyController@Receive');

to

Route::post('/receive','MyController@Receive');

As stated by Curtis, the first thing you need to do is to change the route from get to post . 正如Curtis所说的,您要做的第一件事就是更改从getpost的路线。

Next, you want to send valid json request body with proper Content-Type : application/json header: 接下来,您要发送带有正确Content-Type有效json请求正文: application/json标头:

{  
   "type_3":"Hero"
}

In the controller itself, you do not need to manually retrieve input as Laravel is smart enough to be able to capture and parse json for you. 在控制器本身中,您不需要手动检索输入,因为Laravel足够聪明,可以为您捕获和解析json。

You can access your values using the request object $request->input('type_3') or $request->all() or many more functions for this purpose such as json() , post() etc. 您可以使用请求对象$request->input('type_3')$request->all()或用于此目的的更多函数json()例如json()post()post()

Hope you can figure out based on this. 希望您能以此为基础。

Use post instead get in router 使用帖子代替进入路由器


Route::post('/receive','MyController@Receive');

in controller 在控制器中

public function Receive(Request $request){


    $request->json('type_3'); // hero  get from json

    $request->input('type_3'); // get from input



   return $request->all(); //return all input,request or json and vs vs
 }



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

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