PHP Clear Console
There is no specific built-in function in PHP to clear the console (command-line interface). The console output in PHP is typically meant for displaying results or debug information, and it’s not intended to be cleared like in a traditional terminal environment.
However, if you want to simulate a console-like behavior where the output appears as if it is being cleared and updated dynamically, you can achieve it using some PHP techniques.
Example 1: Simple Console-like Output
<?php
echo "Starting...\n";
// Sleep for 2 seconds to simulate a delay
sleep(2);
// Use backspace character \r to move the cursor to the beginning of the line
echo "Working...\r";
// Sleep again to simulate another delay
sleep(2);
// Final output
echo "Done!\n";
?>
In this example, we use the echo
statement to print output. The backspace character (\r
) is used to move the cursor back to the beginning of the line, creating an illusion of clearing the previous output. The output will appear as “Starting… Working… Done!” sequentially, with a delay of 2 seconds between each message.
Example 2: Using Escape Sequences
<?php
echo "Starting...\n";
// Sleep for 2 seconds
sleep(2);
// Use escape sequence \033[2J to clear the screen
echo "\033[2J"; // Clear screen
// Use escape sequence \033[H to move the cursor to the top left corner of the screen
echo "\033[H"; // Move cursor to top left corner
// Final output
echo "Done!\n";
?>
In this example, we use escape sequences to control the appearance of the console output. The escape sequence \033[2J
clears the screen, and \033[H
moves the cursor to the top left corner of the screen. This creates a visual effect similar to clearing the console. The output will appear as “Starting… Done!” with a 2-second delay before displaying “Done!”.