I have two file.
One is a simple text file that has all the real path link of my scron script with arguments
The other file is my cron script itself.
my contab text file is simply this:
#!/bin/sh
/usr/bin/php -f /home/path/reports/report.php arg1
/usr/bin/php -f /home/path/reports/report.php arg2
The cron script reads the argument in the crontab file and will run accordingly to what argument it is.
report.php --
php $args = $argv[1];
$count = 0;
switch($args){
case 'arg1':
code and create certain file ....
exit;
case 'arg2':
code and create certain file ...
exit;
} // <--- this script runs perfectly if I run script manually through putty commend line, meaning it will run exactly what I want depending on what $argv[1] I put in manual commend line, BUT doesn't run automatically from crontab script
This file does not run and have no idea why, it runs when I manually run report.php through commend line, it works.
One thing i have noticed and got it to kind of work is by changing the report.php to this:
report.php --
$args = $argv[1];
$count = 0;
switch($args){
case ($args ='arg1'): // <- just putting the equal sign makes it work
code and create certain file ....
exit;
case ($args = 'arg2'):
code and create certain file ...
exit;
} // <-- this script was a test to see if it had anything to do with the equal sign, surprisingly script actually worked but only for first case no what matter what argv[1] I had, this is not what I am looking for.
The problem was it only works for the first case, no matter what argument I put in the text file in crobtab it always run the first case. It's probably because I am stating $args = 'arg1', so it always see it as arg1.
So I tried to make it work by doing this instead:
report.php --
$args = $argv[1];
$count = 0;
switch($args){
case ($args =='arg1'): // <- == does not work at all....
code and create certain file ....
exit;
case ($args == 'arg2'):
code and create certain file ...
exit;
} // <--- this script runs perfectly if I run script manually through putty commend line, but not automatically from crontab script
and this runs nothing, it does not pick up my argument at all, just to note this report.php file with the comparison "==" runs perfectly if I run manually on commend line.
What is going on? Why doesn't the cron script read my argument correctly when I use the "==" to find out my arguments from the crontab file.
As for $argv -> "Note: This variable is not available when register_argc_argv is disabled.". I'd suggest to switch to $_SERVER['argv'] and $_SERVER['argc'] (yes, you read correctly) instead of $argv/$argc stuff.
And as for this
case ($args ='arg1'): // <- just putting the equal sign makes it work
man, you clearly do not understand what you doing and what's the difference between ($args=='arg1') and ($args='arg1')!
--[ code for comment bellow ]----
save this as test.php:
<?php
echo $_SERVER['argv'][1] ."\n";
and test it.
$ php test.php abd
abd
The reason the first works is because if you use = instead of == you are setting the variable within the if statement.
Try var_dump($argv) and see if anything is assigned to the variable.
As #arxanas mentions in the comments, your switch is AFU. Read the documentation here. case statements already do the equivalent of $x == [value], so you only need to use case [value]:.
switch($args) {
case ($args =='arg1'):
.
.
.
break;
.
.
.
}
should be
switch($args) {
case 'arg1':
.
.
.
break;
.
.
.
}
Related
I have a for-ever-running PHP script currently started on my machine.
I made some changes in the source code of that script: I've changed the value of one variable in global scope.
Now, if I want these changes to be applied, I could stop and restart the script, but then I would loose all the computations this script has already made. So I want to apply the code changes I made without restarting the PHP interpreter instance.
Can I do that?
What I thought about is maybe plug XDebug in the existing "php.exe" process, and try to alter the variable from there, but I don't know how to.
Another idea would be to use a software that could alter the PHP interpreter memory or symbol table, but I don't know any tool like that.
I started this script without a debuger, but I know that Java, when started with a debuger, has some option to "apply code changes without restarting the Java instance". Is there something similar for PHP interpreter?
There is a sample you might try yourself. Create the PHP file 'myfile.php' with the following code:
<?php
if (ob_get_status()) {
ob_end_clean();
}
$variable = 'Hello';
$i = mt_rand(0, 1000);
while (true) {
$i++;
echo $variable . ' ' . $i . PHP_EOL;
sleep(1);
}
Run it in command line: php -f myfile.php
You are now in my current situation: the script is running for ever, and it contains a dynamic variable $i (that I can not actually know the current value in my real world case, because that real world case has no output).
The challenge is now to change the value of $variable from 'Hello' to 'World' (which represents the variable value I changed in my real world case), but without loosing the current value of $i (that represents the currently done computations).
Remember that you cannot alter the 'myfile.php' code before running the script for the 1st time: you must run the 'myfile.php' with the exact same code as I shown, and then start the challenge.
Not within current file except invoking a function which tries to check a condition:
$variable = function() {
return date('l') == 'Saturday' ? ':)' : ':(';
};
while (true) {
echo $variable() . PHP_EOL;
sleep(1);
}
You cannot, you need to read a new value from somewhere ! You can use a database or a temporary file like this :
file1.php
<?php
file_put_contents('var.tmp','hello');
while(true) {
$var = file_get_contents('var.tmp');
print $var . PHP_EOL;
sleep(1);
}
file2.php
<?php
while(true){
$var = readline('$var > ');
file_put_content('var.tmp',$var);
}
Open 2 terminals, in the first one :
php -f file1.php
And the second one
php -f file2.php
Now you can write the value to the second terminal window and it's going to change in the first one.
I have been wracking my brain and my pc on this one, hoping someone can help me out here.
I have a PHP site that needs to execute a powershell script which in turn executes and executable.
the PHP that calls the .ps1 is
define('updaterPath','C:\\artemis\\DbUpdateUtility1.0.12.2');
define('outputLocation',updaterPath.'\\Output');
$CMD = updaterPath . '\\ArtemisXmlUtil.exe';
$action = 'import';
$args= ' -f' . outputLocation;
$psScriptPath = '.\\get-process.ps1';
$query = shell_exec("powershell -command $psScriptPath -cmd '$CMD' -action '$action' -paras '$args' < NUL");
my .ps1 script is:
param(
[string]$CMD,
[string]$action,
[string]$paras
)
& $CMD $action $paras
Right now, when I echo the full command, it looks perfect and can be copied and pasted into powershell and runs successfully, but when I try to actually execute it from php, it runs with only the $CMD variable and ignores the $action and $paras.
I tried concactenating the variables all into 1 string, but that fails as not even being able to see the executable.
the full command shouls look like:
C:\artemis\DbUpdateUtility1.0.12.2\ArtemisXmlUtil.exe import -fC:\artemis\DbUpdateUtility1.0.12.2\Output
Ok, figured this one out on my own.
The problem is how the command was being executed. Using the "&" forced powershell to ignore the parameters being pass into the script. The correct way, since the command is an executable anyhow, was to build the entire command as a string and pass it all at once to the ps1 file and then change the ps1 file to use the invoke-expression commandlet.
param(
[string]$CMD
)
Invoke-expression $CMD
I am near losing my mind cause of a perl script I want to call via PHP.
I have a PHP Form where I put in a MySQL Query which gets stored in a file and choosing some variables.
If I call any SHELL command like "top" ... everything works fine, but as soon as I try to call my perl script with variables, there are no results at all.
The file where the results should get stored stays empty.
That's the calling part from the PHP File:
if (isset($_POST['submit'])) {
$file = 'query.sql';
$query = $_POST['query'];
file_put_contents($file, $query);
$command = "perl /home/www/host/html/cgi/remote-board-exec.pl -sqlfileexec query.sql > /home/www/host/html/cgi/passthrutest.txt";
exec($command, &$ausgabe, $return_var);
There is no error message and i already tried debug things, but nothing helped :(
Are you sure that perl is being executed? Perhaps you ought to replace the command with 'which perl' just to make sure, and to use the full path to Perl. Another idea is to make sure your:
perl script is executable (use chmod)
ensure it has '#!/usr/bin/perl' (or wherever your path to perl is)
change the command to "/home/www/host/cgi/remote-board-exec.pl..." without the perl command
dump the contents of your output array ($ausgabe) as if the command fails to execute you may find out what is happening.
OK, the question is simple though I can't find a real working solution.
I want to be able to define something while invoking a specific script.
I have tried it like php -d DEBUG_ON myscript.php but it's not working (when testing if (defined("DEBUG_ON")) { } inside the script, it returns false)
Also tried something along the lines of php -r ('define("DEBUG_ON",1);') myscript.php; which doesn't work either.
So, any ideas? (Or any suggestions on how I could achieve the very same effect?)
Use $argv to pass arguments from command line. Then define them accordingly in the beginning of the script.
if(php_sapi_name() === 'cli') {
define('DEBUG_ON', $argv[1]);
}
If you put this code in the beginning of your script, it should then define DEBUG_ON to whatever you pass as argument from commandline: php myscript.php arg1
You can also define($argv[1], $argv[2]); and then use php myscript.php DEBUG_ON 1 to define DEBUG_ON as 1.
I am wanting to call a php file using exec.
When I call it I want to be able to pass a variable through (an id).
I can call echo exec("php /var/www/unity/src/emailer.php"); fine, but the moment I add anything like echo exec("php /var/www/unity/src/emailer.php?id=123"); the exec call fails.
How can I do this?
Your call is failing because you're using a web-style syntax (?parameter=value) with a command-line invokation. I understand what you're thinking, but it simply doesn't work.
You'll want to use $argv instead. See the PHP manual.
To see this in action, write this one-liner to a file:
<?php print_r($argv); ?>
Then invoke it from the command-line with arguments:
php -f /path/to/the/file.php firstparam secondparam
You'll see that $argv contains the name of the script itself as element zero, followed by whatever other parameters you passed in.
try echo exec("php /var/www/unity/src/emailer.php 123"); in your script then read in the commandline parameters.
If you want to pass a GET parameter to it, then it's mandatory to provide a php-cgi binary for invocation:
exec("QUERY_STRING=id=123 php-cgi /var/www/emailer.php");
But this might require more fake CGI environment variables. Hencewhy it is often advisable to rewrite the called script and let it take normal commandline arguments and read them via $_SERVER["argv"].
(You could likewise just fake the php-cgi behaviour with a normal php interpreter and above example by adding parse_str($_SERVER["QUERY_STRING"], $_GET); on top of your script.)
this adapted script shows 2 ways of passing parameters to a php script from a php exec command:
CALLING SCRIPT
<?php
$fileName = '/var/www/ztest/helloworld.php 12';
$options = 'target=13';
exec ("/usr/bin/php -f {$fileName} {$options} > /var/www/ztest/log01.txt 2>&1 &");
echo "ended the calling script";
?>
CALLED SCRIPT
<?php
echo "argv params: ";
print_r($argv);
if ($argv[1]) {echo "got the size right, wilbur! argv element 1: ".$argv[1];}
?>
dont forget to verify execution permissions and to create a log01.txt file with write permissions (your apache user will usually be www-data).
RESULT
argv params: Array
(
[0] => /var/www/ztest/helloworld.php
[1] => 12
[2] => target=13
)
got the size right, wilburargv element 1: 12
choose whatever solution you prefer for passing your parameters, all you need to do is access the argv array and retrieve them in the order that they are passed (file name is the 0 element).
tks #hakre
I know this is an old thread but it helped me solve a problem so I want to offer an expanded solution. I have a php program that is normally called through the web interface and takes a long list of parameters. I wanted to run it in the background with a cron job using shell_exec() and pass a long list of parameters to it. The parameter values change on each run.
Here is my solution: In the calling program I pass a string of parameters that look just like the string a web call would send after the ?. example: sky=blue&roses=red&sun=bright etc. In the called program I check for the existence of $argv[1] and if found I parse the string into the $_GET array. From that point forward the program reads in the parameters just as if they were passed from a web call.
Calling program code:
$pars = escapeshellarg($pars); // must use escapeshellarg()
$output = shell_exec($php_path . ' path/called_program.php ' . $pars); // $pars is the parameter string
Called program code inserted before the $_GET parameters are read:
if(isset($argv[1])){ // if being called from the shell build a $_GET array from the string passed as $argv[1]
$args = explode('&', $argv[1]); // explode the string into an array of Type=Value elements
foreach($args as $arg){
$TV = explode('=', $arg); // now explode each Type and Value into a 2 element array
$_GET[$TV[0]] = $TV[1]; // set the indexes in the $_GET array
}
}
//------------------------
// from this point on the program processes the $_GET array normally just as if it were passed from a web call.
Works great and requires minimal changes to the called program. Hope someone finds it of value.