Simple if statement to make sure that a php file is only run from the cli

Submitted by Micheas on Tue, 02/14/2012 - 15:10

When migrating a site to Drupal, or if your Drupal site has an external data source, it is common to have some custom php files that you only want run from the command line. (migrate users, import blog posts, get new bills, get new apps, etc.)

While it is a good idea to make sure that your webserver and reverse proxies won't run these files there is always the occasional human error. To catch the possible human error putting the following if statement at the beginning of a file is a solid fail-safe to keep the file from being run by visitors to your website.

1  <?php
2 
3    if (!(PHP_SAPI === 'cli')) {
4      die('This script must be run from the command line');
5    }
6   ?>