Pass equivalent $_POST[] array via command line – PHP

  php

Q(Question):

The following code is part of a script actioned by a web form
[PHP]if(isset($_POST[‘report’]))#the form has been submitted
{
if($pls = $_POST[‘pls’]) #hidden variable in pricesCostForm
{
$levels = array();
for($c=0;$c<$pls;$c++)
{
if(isset($_POST[‘level’.$c]))
$levels[] = trim($_POST[‘level’.$c]);
} [/PHP] What do I add to the following command line

C:\apache\xampp\php\php-win.exe "C:\apache\xampp\htdocs\programs\Reports\Prices\pricesReportEntry.php"

so that $_POST[‘report’] is set
$_POST[‘pls’] equals 45
and $_POST[‘level’.42] = ‘TEST’
so that the above code will create the array

$levels[0=>'TEST']

This so the script can run via a scheduled task.
Thanks

A(Answer):

You should be able to fetch command line arguments via the $argv array. Like, if you type into the cmd window:


C:\apache\xampp\php\php-win.exe "C:\Path\To\File\myphpfile.php" first second third

And you had this in the myphpfile.php


<?
print_r($argv);
?>

It should output something like:


Array
(
[0] => myphpfile.php
[1] => first
[2] => second
[3] => third
)

Don’t have a Windows machine to test this on, but it does work on Linux.

A(Answer):

You know, I’ve never attempted PHP from the command line. Like OOP, it’s always intimidated me.

Doesn’t look to hard, actually. So I might give it a shot!

A(Answer):

So I might give it a shit!

I hope you don’t.

A shot will be better.

Once you go OOP you never go back.

Command line is good for cron jobs. (scheduled tasks in Windows)

Maybe you need to clean up temp directories, clean up session table. FTP file somewhere, etc.

You could do it with PHP!

A(Answer):

I hope you don’t.

A shot will be better.

Once you go OOP you never go back.

Command line is good for cron jobs. (scheduled tasks in Windows)

Maybe you need to clean up temp directories, clean up session table. FTP file somewhere, etc.

You could do it with PHP!

Oh dear.

What a bad typo!
I can’t even edit it!

Jeeeez.

A(Answer):

SuperMod to the rescue!

*sound of engine sputtering*

Oops. Forgot; my cape hasn’t been reactivated yet. Well, it’ll be a funny inside joke that we can’t ever tell anyone else about ever.

Anyway. Here’s everything you ever wanted to know and more about running PHP from the command line.

You can’t simulate $_POST variables via CLI. But you could do something like this, if the code had to be runnable from both the command line and the web:


define('IS_CLI', php_sapi_name() == 'cli');
if( IS_CLI )
{
$input =& $argv;
}
else
{
$input =& $_POST;
}
if( isset($input['report']) ) /** and so on */

A(Answer):

Thanks Atli. The argv array, what else.
The same as C hm.
I should have realised.
So I can tag the variables to the command line.
And then use pb_mods suggestion to edit my php
Thanks a lot guys

LEAVE A COMMENT