Home » Php » Call a PHP function from the command line

Call a PHP function from the command line

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a file called address.php with a few functions in it. I want to call a specific function in that file from the command line. How?

The name of the function is called exportAddress and that function expects a single parameter.

How to&Answers:

By using the -r parameter you can run a script in-line.

php -r "require 'address.php'; exportAddress(12345);"

There are no other options. A function in PHP can only be called by a PHP script.

Answer:

Use

php  -r 'include  "/var/www/test/address.php";exportAddress(1);'

where "/var/www/test/arr.php" is the file name, including path, and exportAddress() is a function inside that file.

Answer:

Add this to the top of the file “/var/www/test/address.php”…

foreach ($argv as $i=>$arg )
{
    if ( $arg == "exportAddress" )
    { 
        exportAddress($argv[$i+1]);
    }
}

Then from the command line, execute:

php /var/www/test/address.php exportAddress 12345

Answer:

You can make your file “somefile.php” organized as follows:

function func1(){....}
function func2(){....}
function func3(){....}
....
foreach ($argv AS $arg){
    function_exists($arg) AND call_user_func($arg);
}

Then from the command line or a Linux cronjob, you run the following command:

php /path/to/somefile.php arg1 arg2 arg3 ...

Answer:

To extend on Samer Ata and Simon Rodan’s answers, you can use the following to be able to execute any function with any amount of arguments:

if(isset($argv[1]) && function_exists($argv[1])) {
  $parameters = array_slice($argv, 2);
  call_user_func($argv[1], ...$parameters);
}

This is done by removing the script and function name from $argv and then using the spread operator (...) to interpret each element in the array as an argument to call_user_func.

The operator is supported from PHP 5.6 onward (and 5.5 can do some of the things using functions). You can read more about it in the official PHP documentation.
For completeness, this is also known as argument unpacking.