Home >Backend Development >PHP Tutorial >How to Pass Variables to Command-Line PHP Scripts?

How to Pass Variables to Command-Line PHP Scripts?

DDD
DDDOriginal
2024-11-13 15:36:03690browse

How to Pass Variables to Command-Line PHP Scripts?

Passing Variables to Command-Line PHP Scripts

When running a PHP script from the command line using crontab, you may encounter challenges in passing variables. The syntax you attempted with a query string (myfile.php?type=daily) is not supported in this context.

To resolve this issue, pass the variable as an argument to the PHP executable. Replace your command with:

php myfile.php daily

Within your PHP script, retrieve the variable from the $argv array:

$type = $argv[1]; // Assuming '$argv[0]' contains the script name

Alternative Approaches:

If the script is also used as a webpage, you have two options:

  1. Utilize a shell script with Wget to pass the variable:
#!/bin/sh
wget http://location.to/myfile.php?type=daily
  1. Check whether the script is called from the command line or not within the PHP script:
if (defined('STDIN')) {
  $type = $argv[1];
} else {
  $type = $_GET['type'];
}

Remember to ensure that the $argv array contains the necessary variables and handle edge cases as needed.

The above is the detailed content of How to Pass Variables to Command-Line PHP Scripts?. 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