5
votes

I'm trying to learn now technology - reactPHP. But I'm stacked with starting script. I'd edited it little bit, but I have problem, if I call the react loop, the script is done twice.

I have this code:

<?php
require 'vendor/autoload.php';

$app = function ($request, $response) {
    $date = new DateTime();

    file_put_contents("data.txt", $date->getTimestamp().";", FILE_APPEND);

    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end("Done\n");
};

$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);

$http->on('request', $app);
echo "Server running at http://127.0.0.1:1337\n";

$socket->listen(1337);
$loop->run();

and if I call http://localhost:1337/react/index.php I get in data.txt this

1439849018;1439849018;

I'm expecting only one value.

1
Could you post the output of the method property of the request object as well? It's possible this is because you are seeing a HEAD and GET request. The code appears to be correct ... - Method
Output of $request->method is only "GET". - Karel Poláček
Did you add this to your file_put_contents call or via output to your browser? Also another thing to try is using curl to make the request instead of your browser to better control the experiment - Method
Finally without code $response->writeHead(200, array('Content-Type' => 'text/plain')); $response->end("Done\n"); it works fine. - Karel Poláček

1 Answers

8
votes

I have tested your code and the problem is because your'e testing it in your browser. Your browser send request and then ask for favicon. That's it. On the image from Inspect it's the first and third line. Next time try to run the scripts from cmd.

It's the first and third line.