Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a variable to a PHP script running from the command line

I have a PHP file that is needed to be run from the command line (via crontab). I need to pass type=daily to the file, but I don't know how. I tried:

php myfile.php?type=daily 

but this error was returned:

Could not open input file: myfile.php?type=daily

What can I do?

like image 716
hd. Avatar asked Jul 26 '11 07:07

hd.


People also ask

Can we use PHP for command line scripts?

As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.

What is $argv in PHP?

Introduction. When a PHP script is run from command line, $argv superglobal array contains arguments passed to it. First element in array $argv[0] is always the name of script. This variable is not available if register_argc_argv directive in php. ini is disabled.

How can arguments be passed from the command line into your program?

Command line arguments are passed to the main() method. Here, argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed to the program.


2 Answers

The ?type=daily argument (ending up in the $_GET array) is only valid for web-accessed pages.

You'll need to call it like php myfile.php daily and retrieve that argument from the $argv array (which would be $argv[1], since $argv[0] would be myfile.php).

If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and Wget, and call that from cron:

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

Or check in the PHP file whether it's called from the command line or not:

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

(Note: You'll probably need/want to check if $argv actually contains enough variables and such)

like image 109
PtPazuzu Avatar answered Sep 27 '22 20:09

PtPazuzu


Just pass it as normal parameters and access it in PHP using the $argv array.

php myfile.php daily 

and in myfile.php

$type = $argv[1]; 
like image 45
Christoph Fink Avatar answered Sep 27 '22 20:09

Christoph Fink