Http Server in PHP

Here’s the translation of the HTTP Server example from Go to PHP, formatted in Markdown suitable for Hugo:

Our HTTP server example demonstrates how to create a basic server using PHP’s built-in web server functionality.

<?php

// A fundamental concept in PHP servers is request handling functions.
// These functions take the server and request information as parameters.

function hello($server, $request) {
    // Functions serving as handlers can access server and request information.
    // Here our simple response is just "hello\n".
    echo "hello\n";
}

function headers($server, $request) {
    // This handler does something a little more sophisticated by reading
    // all the HTTP request headers and echoing them into the response body.
    foreach ($server as $name => $value) {
        if (strpos($name, 'HTTP_') === 0) {
            $header = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
            echo "$header: $value\n";
        }
    }
}

// We register our handlers on server routes using a simple if-else structure.
if ($_SERVER['REQUEST_URI'] === '/hello') {
    hello($_SERVER, $_REQUEST);
} elseif ($_SERVER['REQUEST_URI'] === '/headers') {
    headers($_SERVER, $_REQUEST);
} else {
    // Handle 404 Not Found
    http_response_code(404);
    echo "404 Not Found";
}

To run the server, save this code in a file named http-server.php and use PHP’s built-in web server:

$ php -S localhost:8090 http-server.php &

Access the /hello route:

$ curl localhost:8090/hello
hello

This example demonstrates a basic HTTP server in PHP. While PHP doesn’t have a direct equivalent to Go’s http.HandleFunc and http.ListenAndServe, we can achieve similar functionality using PHP’s built-in web server and routing logic.

The hello and headers functions serve as our request handlers. The main routing logic checks the REQUEST_URI to determine which handler to execute.

PHP’s superglobal variables $_SERVER and $_REQUEST provide access to server and request information, similar to the http.ResponseWriter and http.Request in the original example.

Remember that this is a basic example and for production use, you might want to consider using a PHP framework or more robust server setup for better security and performance.