简体   繁体   中英

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. How can I listen to such a request ?

How can I listen to HTTP Post requests ? What will be the URL the POST request has to be sent to? How can I make the program always listening without using hacks such as 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.

You not need any code that wait for a request (eg while(.file_exists("stop.txt")) {} ). That part is covered by the web server, which will call your scripts once it receives a HTTP request.

In your PHP script you need to process the request, which is done by reading the magic variable $_POST .

Here is a simple example for receiving a HTTP POST request with a parameter "payload" that has data in JSON.

Btw. a good way to generate your own POST request is with tools like 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. eg it will be something like localhost/path/to/run.php if you run it locally.

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
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. As in the answer below mine, your server doesnt need to actively "listen";-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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