There is a $_SERVER
array accessible via PHP CLI (testing with PHP 7.4); though it won't contain any HTTP server related variables. The remainder will vary a great deal depending on your environment. I looked at what's available on Windows 10, both Command Prompt and CygWin, along with Centos 7. None include client terminal size or other windowing system information. (As much is true for PHP over HTTP; you'll need Javascript to get the user agent size.)
For reference, if you run php -i
in your terminal, you will see a complete listing of available server and environment variables toward the end. But as I noted, user agent size isn't one of these variables. (Maybe there's a user agent out there that inputs the size; I have no idea!)
We'll have to do something else here, ie. run a shell command and query the underlying platform for the information. First, a gritty "old school" solution (works both in CMD and PS):
// Using PHP as CLI on Windows.
$info = shell_exec('MODE');
Running the MODE
command without arguments gives you something like the following output:
Status for device CON:
----------------------
Lines: 9001
Columns: 120
Keyboard rate: 31
Keyboard delay: 1
Code page: 65001
The "Columns" row states the window width in characters. (Note: This output is locale-specific. You may get "Columnas" or "Oszlopok", etc.) Then let's parse for the number:
preg_match('~Columns:\s+(\d+)~', $info, $match);
$columns = $match[1] ?? null;
The $columns
variable will contain the width in characters of the current command prompt terminal, if the data is available. If not, set default width instead (here simply "null").
This solution will work only on PHP CLI on Windows Command Prompt and Power Shell; or other (presumably Microsoft) terminal applications that support the MODE
command.
There's also a cleaner alternative way to get the column width, if calling PowerShell is an option. The column size / character width is stored in the PS $Host
object:
// Returns the number of columns:
$columns = shell_exec('powershell $Host.UI.RawUI.WindowSize.Width');
For other platforms, you'd have to find an equivalent command. In bash, the equivalent would be tput cols
(which returns the number of columns). As follows:
$columns = shell_exec('tput cols');
This bash command also works with MacOS and CygWin (tested both). Simple enough!
Readers: Please feel free to add notes on getting this data on other platforms. Will integrate to the answer.