Writing

Create a php server using sockets

25/02/2024

10 mins to read

Share article

Http class

class HttpServer
{

  private string $host;
  private string $port;

  public function __construct()
  {
    $this->host = '127.0.0.1';
  }

  public function listen(int $port = 80): void
  {
    $this->port = $port;

    $sock = socket_create(
      domain: AF_INET, //  IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family.
      type: SOCK_STREAM, //  Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.
      protocol: SOL_TCP,
    );

    socket_bind(
      socket: $sock,
      address: $this->host,
      port: $this->port
    ) or die('Could not bind to address');

    echo "\n Listening on http://{$this->host}:{$this->port} \n\n";

    while (1) {
      socket_listen(socket: $sock);
      $client = socket_accept(socket: $sock);

      // $input = socket_read($client, 1024);

      $header = "HTTP/1.1 200 OK \r\n" .
        // "Date: Fri, 31 Dec 1999 23:59:59 GMT \r\n" .
        "Date: " . date('D, d M Y H:i:s T') . " \r\n" .
        "Content-Type: text/html \r\n\r\n";

      $output = $header .
        <<<HTML
        <!DOCTYPE html>
        <html lang="en">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My website</title>
          </head>
          <body>It works!</body>
        </html>
      HTML;

      socket_write(
        socket: $client,
        data: $output,
        length: strlen($output)
      );
      socket_close(socket: $client);
    }
  }
};

Run the server

<?php
set_time_limit(0);

$http = new HttpServer();
$http->listen(3001);
© 2025, Nikodem Kedzierski - All rights reserved.