Clear CMD-shell with php

2020-06-19 05:50发布

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?

6条回答
混吃等死
2楼-- · 2020-06-19 05:55

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++;
}
查看更多
走好不送
3楼-- · 2020-06-19 05:59

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.

查看更多
爷、活的狠高调
4楼-- · 2020-06-19 06:08

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.

查看更多
Bombasti
5楼-- · 2020-06-19 06:12

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

查看更多
We Are One
6楼-- · 2020-06-19 06:16

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++;
}
查看更多
做自己的国王
7楼-- · 2020-06-19 06:21

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.

查看更多
登录 后发表回答