Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell run/execute php script with parameters

I need to execute a php file with parameters through shell.

here is how I would run the php file:

php -q htdocs/file.php

I need to have the parameter 'show' be passed through and

php -q htdocs/file.php?show=show_name

doesn't work

If someone could spell out to me what command to execute to get the php file to execute with set parameters, it would be much appreciated. If not, try to lead me the right direction.

like image 476
Patrick Lorio Avatar asked Jul 20 '11 15:07

Patrick Lorio


People also ask

How do I run a shell script in PHP?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string. The shell_exec is an alias for the backtick operator, for those used to *nix.

How do I pass a command line argument in PHP?

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.

How do I run a PHP script in Linux?

You can execute linux commands within a php script - all you have to do is put the command line in brackits (`). And also concentrate on exec() , this and shell_exec() ..


2 Answers

test.php:

<?php print_r($argv); ?> 

Shell:

$ php -q test.php foo bar Array (     [0] => test.php     [1] => foo     [2] => bar ) 
like image 150
schneck Avatar answered Sep 18 '22 04:09

schneck


If you have webserver (not only just php interpreter installed, but LAMP/LNMP/etc) - just try this

wget -O - -q -t 1 "http://mysite.com/file.php?show=show_name" >/dev/null 2>&1 

where:

  • « -O - » — (Letter "O", not zero!) redirect "downloaded html" to stdout
  • « >/dev/null 2>&1 » — redirect stdout & stderr output to nowhere
  • « -q » — quiet wget run
  • « -t 1 » — just 1 try to connect (not like default 20)

In PHP's "exec" it'll be smth like this:

function exec_local_url($url) {   exec('/usr/bin/wget -O - -q -t 1 "http://'. $_SERVER['HTTP_HOST'] .'/'     . addslashes($url) . '" >/dev/null 2>&1'   ); }  // ...  exec_local_url("file.php?show=show_name"); exec_local_url("myframework/seo-readable/show/show_name"); 

So, you don't need to change your scripts to handle argc/argv, and may use $_GET as usually do.

If you want jobs runned in background - see for ex. Unix/Windows, Setup background process? from php code

I use approach with wget in my cron jobs; hope it helps.

like image 31
FlameStorm Avatar answered Sep 20 '22 04:09

FlameStorm