calling shell_exec(“php myscript.php”) goe

2019-08-11 09:28发布

问题:

I decided to fork out my php script because it takes too long to run. When I ran it shell_exec() call on a local linux machine, I did not see the infinite loop problem, but on a hosted machine, the script went into an infinite loop. I reduced the code to the minimum and I hope someone can help me see the problem here:

3 scripts are involved:
test_shell.php --> issues shell_exec() to forkphp.sh --> which issues a command "path/to/php write_hello_world.php"

starting from top to bottom order, first the test_shell.php script:

<?php
    if(function_exists('shell_exec')) {
            echo "shell_exec() is enabled";
    }

    $cmd = "./forkphp.sh > /dev/null 2>&1 &";
    echo "<br/> About to shell_exec($cmd)<br/>";
    $out = shell_exec($cmd);
    echo $out;

?>

Here is forkphp.sh:

#!/bin/bash
# About to run /usr/bin/php  write_hello_world.php
echo $(/usr/bin/php write_hello_world.php)

Finally, here is write_hello_word.php :

<?php
$data = "This is a test : testing \n testing \n ";

file_put_contents ("deleteme.txt",$data);

?>

This gets an infinite loop where file 'deleteme.txt' continuously re-written . I am only guessing that I maybe misusing the '$' somewhere? Thank you in advance for help.

回答1:

Pass the FILE_APPEND flag to file_put_contents(), otherwise the file would being overwritten again and again:

file_put_contents ("deleteme.txt",$data, FILE_APPEND);