function ServerCommand::openBrowser

Same name in other branches
  1. 9 core/lib/Drupal/Core/Command/ServerCommand.php \Drupal\Core\Command\ServerCommand::openBrowser()
  2. 10 core/lib/Drupal/Core/Command/ServerCommand.php \Drupal\Core\Command\ServerCommand::openBrowser()
  3. 11.x core/lib/Drupal/Core/Command/ServerCommand.php \Drupal\Core\Command\ServerCommand::openBrowser()

Opens a URL in your system default browser.

Parameters

string $url: The URL to browser to.

\Symfony\Component\Console\Style\SymfonyStyle $io: The IO.

1 call to ServerCommand::openBrowser()
ServerCommand::start in core/lib/Drupal/Core/Command/ServerCommand.php
Starts up a webserver with a running Drupal.

File

core/lib/Drupal/Core/Command/ServerCommand.php, line 141

Class

ServerCommand
Runs the PHP webserver for a Drupal site for local testing/development.

Namespace

Drupal\Core\Command

Code

protected function openBrowser($url, SymfonyStyle $io) {
    $is_windows = defined('PHP_WINDOWS_VERSION_BUILD');
    if ($is_windows) {
        // Handle escaping ourselves.
        $cmd = 'start "web" "' . $url . '""';
    }
    else {
        $url = escapeshellarg($url);
    }
    $is_linux = (new Process('which xdg-open'))->run();
    $is_osx = (new Process('which open'))->run();
    if ($is_linux === 0) {
        $cmd = 'xdg-open ' . $url;
    }
    elseif ($is_osx === 0) {
        $cmd = 'open ' . $url;
    }
    if (empty($cmd)) {
        $io->getErrorStyle()
            ->error('No suitable browser opening command found, open yourself: ' . $url);
        return;
    }
    if ($io->isVerbose()) {
        $io->writeln("<info>Browser command:</info> {$cmd}");
    }
    // Need to escape double quotes in the command so the PHP will work.
    $cmd = str_replace('"', '\\"', $cmd);
    // Sleep for 2 seconds before opening the browser. This allows the command
    // to start up the PHP built-in webserver in the meantime. We use a
    // PhpProcess so that Windows powershell users also get a browser opened
    // for them.
    $php = "<?php sleep(2); passthru(\"{$cmd}\"); ?>";
    $process = new PhpProcess($php);
    $process->start();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.