Jump to content

Receiving POST data in React HTTP Server


NotionCommotion

Recommended Posts

GET data seems pretty straight forward, but not so with POST data.  It seems to work, however, that does not necessarily mean it is right.  Am I doing it right?  Thanks

<?php
require 'vendor/autoload.php';
use React\EventLoop\Factory;
use React\Http\Server as HttpServer;
use React\Socket\Server as SocketServer;

set_time_limit(0);

$port='1337';
//$host='0.0.0.0';
//$host='127.0.0.1';
$host='192.168.1.200';
//$host='192.168.1.201';

$loop = Factory::create();
$http_socket = new SocketServer($loop);
$http = new HttpServer($http_socket);
$http->on('request', function ($request, $response) {
    switch($request->getMethod()) {
        case 'GET':
            $response->writeHead(200, array('Content-Type' => 'text/plain'));
            $query = $request->getQuery();
            echo print_r($query,1) . PHP_EOL;
            $response->end(print_r($query,1));
            break;
        case 'POST':
            $requestBody = '';
            $headers = $request->getHeaders();
            $contentLength = (int)$headers['Content-Length'];
            $receivedData = 0;
            $request->on('data',function($data) use ($request, $response, &$requestBody, &$receivedData, $contentLength) {
                $requestBody.=$data;
                $receivedData+=strlen($data);
                if ($receivedData>=$contentLength) {
                    parse_str($requestBody, $query);
                    $response->writeHead(200, array('Content-Type' => 'text/plain'));
                    echo print_r($query,1) . PHP_EOL;
                    $response->end(print_r($query,1));
                }
            });
            break;
    }
});


$http_socket->listen($port, $host);
$loop->run();
Edited by NotionCommotion
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.