Home > Backend Development > PHP Tutorial > How do I pass variables to a PHP script executed from the command line?

How do I pass variables to a PHP script executed from the command line?

Mary-Kate Olsen
Release: 2024-11-11 08:41:02
Original
533 people have browsed it

How do I pass variables to a PHP script executed from the command line?

Passing Variables to PHP Scripts from the Command Line

When executing PHP scripts via the command line, such as through crontab, it's useful to pass variables to the script for customization and control. However, the traditional method of appending query parameters to the script's path, like php myfile.php?type=daily, may not work.

The $argv Array

For command-line execution, PHP provides the $argv array, which contains arguments passed to the script. The first element, $argv[0], is the script's filename. Subsequent elements, starting from $argv[1], contain the additional arguments.

Passing Arguments Via $argv

To pass the type argument in this case, simply call the script as follows:

php myfile.php daily
Copy after login

Within the PHP script, you can then retrieve the argument using $argv[1]:

$type = $argv[1];
Copy after login

Web Page Consideration

If your PHP script is also used as a web page, you'll need to distinguish between command-line and web access. One approach is to check if STDIN is defined, which typically indicates command-line execution:

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

Alternatively, you can use a shell script and Wget to access the script via the web from the command line:

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

By understanding the use of $argv and considering web access, you can effectively pass variables to PHP scripts running from the command line.

The above is the detailed content of How do I pass variables to a PHP script executed from the command line?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template