SimpleSAML\Test\BuiltInServer::start PHP Method

start() public method

This method will wait up to 5 seconds for the server to start. When it returns an address, it is guaranteed that the server has started and is listening for connections. If it returns false on the other hand, there will be no guarantee that the server started properly.
public start ( ) : string
return string The address where the server is listening for connections, or false if the server failed to start for some reason.
    public function start()
    {
        $port = mt_rand(1025, 65535);
        $this->address = 'localhost:' . $port;
        $command = sprintf('php -S %s -t %s %s >> /dev/null 2>&1 & echo $!', $this->address, $this->docroot, $this->router);
        // execute the command and store the process ID
        $output = array();
        exec($command, $output);
        $this->pid = (int) $output[0];
        // wait until it's listening for connections to avoid race conditions
        $start = microtime(true);
        while (($sock = @fsockopen('localhost', $port, $errno, $errstr, 10)) === false) {
            // set a 5 secs timeout waiting for the server to start
            if (microtime(true) > $start + 5) {
                $this->pid = false;
                // signal failure
                $this->address = false;
                break;
            }
        }
        if ($sock !== false) {
            fclose($sock);
        }
        return $this->address;
    }

Usage Example

 /**
  * The setup method that is run before any tests in this class.
  */
 protected function setup()
 {
     $this->server = new BuiltInServer('configLoader');
     $this->server_addr = $this->server->start();
     $this->server_pid = $this->server->getPid();
     $this->shared_file = sys_get_temp_dir() . '/' . $this->server_pid . '.lock';
     @unlink($this->shared_file);
     // remove it if it exists
 }