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

How to Pass Variables to Command-Line PHP Scripts?

DDD
Release: 2024-11-13 15:36:03
Original
638 people have browsed it

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
Copy after login

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

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

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
Copy after login
  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'];
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template