PHP code example of unirend / php-static-server

1. Go to this page and download the library: Download unirend/php-static-server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

unirend / php-static-server example snippets



Unirend\StaticServer\StaticServer;

$server = new StaticServer([
  'buildDir' => __DIR__ . '/build/client',
]);

$server->serve();

'singleAssets' => [
    '/robots.txt'  => 'robots.txt',
    '/favicon.ico' => 'favicon.ico',
    '/sitemap.xml' => 'sitemap.xml',
],

'assetFolders' => [
    '/assets' => 'assets',
    // Per-folder config: opt another folder of hashed files into detection
    '/downloads' => ['path' => 'downloads', 'detectImmutableAssets' => true],
    // Verbatim files: plain string, detection off by default
    '/.well-known' => '.well-known',
],

$server = new StaticServer([
  'buildDir' => __DIR__ . '/build/client',
]);
// Exceptions are logged to PHP's error log automatically

$server = new StaticServer([
  'buildDir' => __DIR__ . '/build/client',
  'onError' => function (\Throwable $e, string $context): void {
    // Send to your logging service, write to a custom log file, etc.
    myLogger()->error($context . ': ' . $e->getMessage(), [
      'exception' => $e,
    ]);
  },
]);

$server = new StaticServer([
  'buildDir' => __DIR__ . '/build/client',
  'logErrors' => false, // Disables error_log() — onError hook still fires if set
]);

$server = new StaticServer([
  'buildDir' => __DIR__ . '/build/client',
  'assetFolders' => ['/assets' => 'assets'],
]);

// Simple endpoint
$server->addRoute('POST', '/api/contact', function (
  array $params,
  array $body,
): void {
  // $body is parsed from JSON body or $_POST
  $name = $body['name'] ?? 'stranger';

  // send email, save to DB, etc.

  header('Content-Type: application/json');
  echo json_encode(['ok' => true]);
});

// Dynamic route with named :param segments
$server->addRoute('GET', '/api/posts/:id', function (
  array $params,
  array $body,
): void {
  $id = (int) $params['id'];
  header('Content-Type: application/json');
  echo json_encode(['id' => $id]);
});

// Start serving requests — handles routing, static files, and error pages
// (Your web server with PHP handles the actual HTTP listening)
$server->serve();
bash
composer 
bash
cp vendor/unirend/php-static-server/templates/index.php .
cp vendor/unirend/php-static-server/templates/.htaccess .
bash
php -S localhost:8080 index.php
bash
bun run php-install-deps
bash
bun run php-test
bash
cd unirend-php
composer install
cd demo
php -S localhost:8080 index.php
bash
bun run php-publish