Home > Backend Development > PHP Tutorial > How Can I Pass Variables to PHP Scripts from the Command Line?

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

Barbara Streisand
Release: 2024-11-12 18:19:02
Original
994 people have browsed it

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

Pass Variables to PHP Scripts via Command Line

When running PHP scripts from the command line, it's necessary to pass variables to control the script's behavior. However, the approach commonly used for web pages, myfile.php?type=daily, may not work.

Parameter Passing via $argv

To pass variables from the command line, use the $argv array. When running php myfile.php daily, $argv[1] will contain the value "daily". This is in contrast to web pages, where query string parameters are stored in $_GET.

Alternatives for Web Page Usage

If the PHP script also serves as a web page, there are two possible solutions:

  1. Shell Script and Wget: Create a shell script that invokes Wget to fetch the page with the required parameter:
#!/bin/sh
wget http://location.to/myfile.php?type=daily
Copy after login

Run this script from cron to pass the variable.

  1. Detection within PHP: Check within the PHP script whether it's being accessed via command line or web. if (defined('STDIN')) {
    $type = $argv[1];
    } else {
    $type = $_GET['type'];
    }

Limitations

Note that using $argv[1] assumes that the command-line call provides the necessary parameter. Always check if $argv contains enough variables.

The above is the detailed content of How Can I Pass Variables to PHP Scripts 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