When troubleshooting a problem with a specific Drupal page, the ability to simulate a request to this page via Drush can be helpful in the debugging process. This how-to explains why and how to render a Drupal page using Drush.
Why would I use Drush to render Drupal pages?
- PHP errors and warnings that occur during the rendering process are output directly to the command-line in real time, obviating the need to search through your sites logs for these errors.
- Server variables involved in controlling the request's output can be easily manipulated for additional control over Drupal's behavior when rendering the page.
- Rendering a page via command-line can provide a workaround for debugging Drupal application issues that result in network performance problems (e.g: HTTP timeouts) that might otherwise impact your ability to render pages with a standard HTTP request.
How do I use Drush to render a Drupal page?
Rendering a Drupal page via Drush requires the use of Drush's php-eval command to execute the page rendering mechanism found in Drupal's index.php file. The command relies on PHP's global
$_SERVER variables to gather information about the type of request you're making. Helpfully, Drush automatically populates several of the key server variables used by Drupal for this purpose, and allows you to control them via Drush's command-line options. For example:
--uri=[full request URL]option allows you to populate the HTTP host, request URI, querystring, port, and all other variables that might be populated by the URL of an incoming web request. The value of this option tells Drupal which page you're trying to render.
--user=[uid]option allows you to simulate a request as a specific Drupal user. By default, Drupal will use the anonymous user (i.e:
--user=0) for this purpose.
Additionally, you assign values directly to
$_POST and other PHP superglobals in the body of the php-eval command itself, prior to executing the code that renders the page.
At their most basic, the Drush commands you'd use to render a page on your Drupal site are as follows:
For Drupal 7:
drush --user=0 --uri=http://www.example.com/path/to/page php-eval ' menu_execute_active_handler();'
For Drupal 8:
drush --user=0 --uri=http://www.example.com/path/to/page php-eval ' (new Drupal\Core\DrupalKernel("prod", new Composer\Autoload\ClassLoader()))->handle(Symfony\Component\HttpFoundation\Request::createFromGlobals())->send();'
Both of the commands above will render the page at http://www.example.com/path/to/page for an anonymous user (UID 0). Changing the
--user options being passed into Drush, or adding additional PHP code to the php-eval commands being executed above can change the way that Drupal behaves when rendering the page, and may change the output that you receive in response to these commands.