ryoakg
2/9/2017 - 2:18 PM

multi-port-built-in-web-server.php

<?php
if (PHP_SAPI === 'cli') {
  if (in_array('--help', $argv) || in_array('-h', $argv)){
    echo 'Usage:' . PHP_EOL;
    echo "  php [<PORT1> [<PORT2> [<PHP BINARY>]]]" . PHP_EOL;
    exit;
  }
  $script1 = $argv[0].'.1';
  $script2 = $argv[0].'.2';
  $port1 = (int)@$argv[1] | 8080;
  $port2 = (int)@$argv[2] | 8081;
  $php_bin = (string)@$argv[3] | $_SERVER['_'];

  $pid = pcntl_fork();
  if ($pid === -1) {
    echo 'pcntl_fork() failed.' . PHP_EOL;
  } else if ($pid) {
    @symlink($argv[0], $script1);
    exec("{$php_bin} -S localhost:{$port1} {$script1}");
    pcntl_waitpid($pid, $status);
  } else {
    @symlink($argv[0], $script2);
    exec("{$php_bin} -S localhost:{$port2} {$script2}");
  }
  exit;
}

$site_no = substr(strrchr($_SERVER['SCRIPT_FILENAME'], '.'), 1);
call_user_func("site{$site_no}");

function site1(){
  switch(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)){
    default:
      page1();
  }
}

function site2(){
  switch(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)){
    default:
      page2();
  }
}

function page1(){ ?>
  <html lang="ja">
    <head>
      <title>aaa</title>
    </head>
    <body>
      aaa
    </body>
  </html>
<?php }

function page2(){ ?>
  <html lang="ja">
    <head>
      <title>bbb</title>
    </head>
    <body>
      bbb
    </body>
  </html>
<?php }