Home  >  Article  >  Backend Development  >  How to Pass Variables to PHP Scripts from the Command Line?

How to Pass Variables to PHP Scripts from the Command Line?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 22:57:02888browse

How to Pass Variables to PHP Scripts from the Command Line?

Passing Variables to PHP Scripts from the Command Line

When executing PHP scripts from the command line, it's often necessary to pass in variables. However, attempts to achieve this using the traditional $_GET method (e.g., php myfile.php?type=daily) may result in the "Could not open input file" error.

This is because the $_GET array is typically only accessible when a script is executed as a webpage. To handle variable passing from the command line, alternative methods must be utilized.

Using $argv Array

When running a PHP script from the command line, variables can be passed in using the $argv array. This array contains the arguments provided after the script name. For example, to pass the type=daily variable, you would call the script as follows:

php myfile.php daily

In the PHP script, you can retrieve the variable using $argv[1].

Handling Web and Command Line Execution

If a PHP script is intended for both web and command line execution, you can check whether the script is being called from the command line using the STDIN constant. The following code snippet illustrates this:

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

In this example, if the script is being executed from the command line, the type variable will be retrieved from $argv[1]. Otherwise, it will be retrieved from $_GET['type'].

Using a Shell Script and Wget

Another option for passing variables from the command line is to use a shell script and Wget. This can be useful if you need to pass a variable as part of a URL. The following shell script demonstrates this approach:

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

In this script, the variable type=daily is passed as part of the URL. The script can then be called from cron to execute the PHP script with the specified variable.

The above is the detailed content of How to Pass Variables to PHP Scripts from the Command Line?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn