Pass a variable to a PHP script running from the command line

152,199

Solution 1

The ?type=daily argument (ending up in the $_GET array) is only valid for web-accessed pages.

You'll need to call it like php myfile.php daily and retrieve that argument from the $argv array (which would be $argv[1], since $argv[0] would be myfile.php).

If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and Wget, and call that from cron:

#!/bin/sh
wget http://location.to/myfile.php?type=daily

Or check in the PHP file whether it's called from the command line or not:

if (defined('STDIN')) {
  $type = $argv[1];
} else {
  $type = $_GET['type'];
}

(Note: You'll probably need/want to check if $argv actually contains enough variables and such)

Solution 2

Just pass it as normal parameters and access it in PHP using the $argv array.

php myfile.php daily

and in myfile.php

$type = $argv[1];

Solution 3

These lines will convert the arguments of a CLI call like php myfile.php "type=daily&foo=bar" into the well known $_GET-array:

if (!empty($argv[1])) {
    parse_str($argv[1], $_GET);
}

Though it is rather messy to overwrite the global $_GET-array, it converts all your scripts quickly to accept CLI arguments.

See parse_str for details.


If you want the more traditional CLI style like php myfile.php type=daily foo=bar a small function can convert this into an associative array compatible with a $_GET-array:

// Convert $argv into associative array
function parse_argv(array $argv): array
{
    $request = [];
    foreach ($argv as $i => $a) {
        if (!$i) {
            continue;
        }

        if (preg_match('/^-*(.+?)=(.+)$/', $a, $matches)) {
            $request[$matches[1]] = $matches[2];
        } else {
            $request[$a] = true;
        }
    }

    return $request;
}

if (!empty($argv[1])) {
    $_GET = parse_argv($argv);
}

Solution 4

Using the getopt() function, we can also read a parameter from the command line. Just pass a value with the php running command:

php abc.php --name=xyz

File abc.php

$val = getopt(null, ["name:"]);
print_r($val); // Output: ['name' => 'xyz'];

Solution 5

Parameters send by index like other applications:

php myfile.php type=daily

And then you can get them like this:

<?php
    if (count($argv) == 0) 
        exit;

    foreach ($argv as $arg)
        echo $arg;
?>
Share:
152,199
hd.
Author by

hd.

Updated on January 24, 2022

Comments

  • hd.
    hd. over 2 years

    I have a PHP file that is needed to be run from the command line (via crontab). I need to pass type=daily to the file, but I don't know how. I tried:

    php myfile.php?type=daily
    

    but this error was returned:

    Could not open input file: myfile.php?type=daily

    What can I do?

  • spybart
    spybart over 8 years
    this isn't really that convenient, it doesn't separate out the key and value, it just passes the value "type=daily"
  • J. Chomel
    J. Chomel almost 8 years
    While this may answer the question, consider adding details on how this solution solves the issue. Kindly refer to stackoverflow.com/help/how-to-answer .
  • easyaspi
    easyaspi almost 8 years
    Save this code in file myfile.php and run as 'php myfile.php type=daily' if you add var_dump($b); before the ?> tag, you will see that the array $b contains type => daily.
  • demenvil
    demenvil almost 8 years
    Use : if (isset($argv[1])) { echo . $argv[1]; } else { die('no ! '); }
  • Reado
    Reado over 7 years
    Perfect answer! Thanks!
  • ViliusL
    ViliusL over 5 years
    Recommended way is to use getopt()
  • CodeForGood
    CodeForGood over 3 years
    What does defined('STDIN') do?
  • Peter Mortensen
    Peter Mortensen over 3 years
    This seems to be a response to Subdigger's answer.
  • Peter Mortensen
    Peter Mortensen over 3 years
    Yes, I think this is what the OP actually was looking for (running (almost) the same (web) PHP script in a command-line context).
  • Peter Mortensen
    Peter Mortensen over 3 years
    Who or what is "sep16"?
  • K3---rnc
    K3---rnc over 3 years
    @PeterMortensen The stated author of the post I link to.
  • Peter Mortensen
    Peter Mortensen almost 3 years
    Can you elaborate in you answer? E.g., with example code on how to actually do it?
  • Peter Mortensen
    Peter Mortensen almost 3 years
    What is the purpose of $$key = $val;?
  • emmanuel
    emmanuel almost 3 years
    to use directly variable without beeing in a array extract($_REQUEST) do the job too