简体   繁体   English

如何正确收听 PHP 中的 HTTP JSON POST 请求?

[英]How can I properly listen to HTTP JSON POST requests in PHP?

I need to listen to a HTTP POST request and respond to it.我需要听取 HTTP POST 请求并做出响应。 How can I listen to such a request ?我怎么能听这样的请求

How can I listen to HTTP Post requests ?如何收听 HTTP 发布请求 What will be the URL the POST request has to be sent to? POST 请求必须发送到的 URL 是什么? How can I make the program always listening without using hacks such as while(.file_exists("stop.txt")) {} ?如何在不使用诸如while(.file_exists("stop.txt")) {}的技巧的情况下使程序始终收听?

Please note that I'm NOT coding a website请注意,我不是在编写网站代码

To listen to a POST request with a PHP program all you need to do is have a web server running with a PHP script that accepts a POST request.要使用 PHP 程序收听 POST 请求,您需要做的就是让 web 服务器运行 PHP 脚本并接受 POST 请求。

You not need any code that wait for a request (eg while(.file_exists("stop.txt")) {} ).您不需要任何等待请求的代码(例如while(.file_exists("stop.txt")) {} )。 That part is covered by the web server, which will call your scripts once it receives a HTTP request.该部分由 web 服务器覆盖,一旦收到 HTTP 请求,它将调用您的脚本。

In your PHP script you need to process the request, which is done by reading the magic variable $_POST .在您的 PHP 脚本中,您需要处理请求,这是通过读取魔术变量$_POST来完成的。

Here is a simple example for receiving a HTTP POST request with a parameter "payload" that has data in JSON.下面是一个接收 HTTP POST 请求的简单示例,该请求带有参数“payload”,该参数包含 JSON 中的数据。

Btw.顺便提一句。 a good way to generate your own POST request is with tools like Postman ( https://www.getpostman.com/ )生成自己的 POST 请求的一个好方法是使用 Postman ( https://www.getpostman.com/ ) 等工具

<?php

$request_json = $_POST["payload"];
$request = json_decode($request_json);
print_r($request);

The URL will depend on where the webserver is running. URL 将取决于网络服务器的运行位置。 eg it will be something like localhost/path/to/run.php if you run it locally.例如,如果您在本地运行它,它将类似于localhost/path/to/run.php

I dont know, if I get your question correct.我不知道,如果我得到你的问题是正确的。 If you just want to answer, if a post request is send to you, you could write a simple php script:如果您只是想回答,如果发送请求给您,您可以编写一个简单的 php 脚本:

<?php
if (!empty($_POST)):
 // Post was sent and you can do stuff with it and response
 $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
 echo json_encode($arr);
else:
 echo "Nothing to see here, because no post was sent";
endif;
?>

So this script answers when someone sends a post to that uri, where the script is located.因此,当有人向该脚本所在的 uri 发送帖子时,此脚本会回答。 As in the answer below mine, your server doesnt need to actively "listen";-)正如我在下面的答案中一样,您的服务器不需要主动“倾听”;-)

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

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