Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear CMD-shell with php

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?

like image 914
Black Avatar asked Apr 12 '16 09:04

Black


4 Answers

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.

like image 139
Chris Avatar answered Sep 18 '22 04:09

Chris


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++;
}
like image 45
Naisa purushotham Avatar answered Sep 19 '22 04:09

Naisa purushotham


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.

like image 33
fedorqui 'SO stop harming' Avatar answered Sep 21 '22 04:09

fedorqui 'SO stop harming'


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...

like image 45
Frank Nocke Avatar answered Sep 20 '22 04:09

Frank Nocke