system() function in PHP prints variable 2 times

12,858

Solution 1

Use exec instead of system

http://us.php.net/manual/en/function.system.php#94262

Solution 2

system displays whatever the program outputs and returns the last line of output.

exec displays nothing and returns the last line of output.

passthru displays whatever the program outputs and returns nothing.

Solution 3

According to the manual -- see system() :

system() is just like the C version of the function in that it executes the given command and outputs the result.

Which explains the first blah


And :

Returns the last line of the command output on success

And you are echoing the returned value -- which explains the second blah.


If you want to execute a command, and get the full output to a variable, you should take a look at exec, or shell_exec.

The first one will get you all the lines of the output to an array (see the second paramater) ; and the second one will get you the full output as a string.

Solution 4

Use exec instead. To get all the output, rather than just the last line do this:

$variable = array();
$lastline = exec("cat /home/maxor/test.txt", $variable);
echo implode("\n", $variable);
Share:
12,858
lauriys
Author by

lauriys

Updated on June 05, 2022

Comments

  • lauriys
    lauriys almost 2 years

    Stupid question, this code:

    <?php
    $variable = system("cat /home/maxor/test.txt");
    echo $variable;
    ?>
    

    with file test.txt:

    blah
    

    prints:

    blah
    blah
    

    What can I do with system() function to not print nothing so I get 1 "blah"???