Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run php script from command line with variable

Tags:

I want to run a PHP script from the command line, but I also want to set a variable for that script.

Browser version: script.php?var=3

Command line: php -f script.php (but how do I give it the variable containing 3?)

like image 518
Hintswen Avatar asked Jun 10 '09 08:06

Hintswen


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.

How do I pass a command line argument to a PHP script?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

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.


1 Answers

Script:

<?php  // number of arguments passed to the script var_dump($argc);  // the arguments as an array. first argument is always the script name var_dump($argv); 

Command:

$ php -f test.php foo bar baz int(4) array(4) {   [0]=>   string(8) "test.php"   [1]=>   string(3) "foo"   [2]=>   string(3) "bar"   [3]=>   string(3) "baz" } 

Also, take a look at using PHP from the command line.

like image 98
Ionuț G. Stan Avatar answered Oct 05 '22 22:10

Ionuț G. Stan