Search code examples
phphttppostwebhooksslack

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


Solution

  • 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 (e.g. 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. e.g. it will be something like localhost/path/to/run.php if you run it locally.