PHP CLI – Restrict to CLI Only

|

Sometimes it’s easier to run a PHP script than to run a UNIX bash/shell script, this code below will require the use of PHP CLI and prevent it from running in a web browser.

Typically a good idea to place the PHP file out of the web directory as well.

This code will not really do much but you can get the idea of how it works.

<?php
 
// Restrict access to this file - start
if (php_sapi_name() != 'cli'){
    exit;
}
// Restrict access to this file - stop
 
// Require CLI Parameter - Start
// Require a username to get passed via CLI, if no username is received we will display an error at the end
if (isset($argv[1]) && ('' != trim($argv[1])))
{
    $username = $argv[1];
    echo $username;
}
else
{
    echo "No Parameter sent, exiting now";
    exit;
}
?>
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.