5

I have this simple php script which outputs a string every second.

<?php
$i = 1;

while(1)
{
    exec("cls");    //<- Does not work
    echo "test_".$i."\n";

    sleep(1);
    $i++;
}

I execute the script in the command shell on windows (php myscript.php) and try to clear the command shell before every cycle. But I don't get it to work. Any ideas?

Black
  • 18,150
  • 39
  • 158
  • 271

6 Answers6

3

How about this?

<?php
$i = 1;
echo str_repeat("\n", 300); // Clears buffer history, only executes once
while(1)
{
    echo "test_".$i."\r"; // Now uses carriage return instead of new line

    sleep(1);
    $i++;
}

the str_repeat() function executes outside of the while loop, and instead of ending each echo with a new line, it moves the pointer back to the existing line, and writes over the top of it.

Chris
  • 96
  • 2
2

can you check this solution

$i = 1;
echo PHP_OS;

while(1)
{
    if(PHP_OS=="Linux")
    {
        system('clear');
    }
    else
        system('cls');
    echo "test_".$i."\n";

    sleep(1);
    $i++;
}
Naisa purushotham
  • 905
  • 10
  • 18
1

Apparently, you have to store the output of the variable and then print it to have it clear the screen successfully:

$clear = exec("cls");
print($clear);

All together:

<?php
$i = 1;

while(1)
{
    $clear = exec("cls");
    print($clear);
    echo "test_".$i."\n";

    sleep(1);
    $i++;
}

I tested it on Linux with clear instead of cls (the equivalent command) and it worked fine.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Oh, too bad. I tested on Linux and expected Windows to behave similarly by adapting the command (from `clear` to `cls`). – fedorqui Apr 18 '16 at 09:09
1

Duplicate of ➝ this question

Under Windows, no such thing as

@exec('cls');

Sorry! All you could possibly do is hunt for an executable (not the cmd built-in command) like here...

Community
  • 1
  • 1
Frank N
  • 9,625
  • 4
  • 80
  • 110
0

You have to print the output to the terminal:

<?php
$i = 1;

while(1)
{
    exec("cls", $clearOutput);
    foreach($clearOutput as $cleanLine)
    {
         echo $cleanLine;
    }
    echo "test_".$i."\n";

    sleep(1);
    $i++;
}
Nadir
  • 1,799
  • 12
  • 20
0

if it is linux server use following command (clear) if it is window server use cls i hope it will work

$i = 1;

while(1)
{
    exec("clear");    //<- This will work
    echo "test_".$i."\n";

    sleep(1);
    $i++;
}

second solution

<?php
$i = 1;
echo PHP_OS;

while(1)
{
    if(PHP_OS=="Linux")
     {
        $clear = exec("clear");
        print($clear);
      }
    else
    exec("cls");
    echo "test_".$i."\n";

    sleep(1);
    $i++;
}

This one worked for me, tested also.

Naisa purushotham
  • 905
  • 10
  • 18