When developing PHP applications, sometimes you need to execute system commands to complete some specific tasks. Due to the differences in command formats and behaviors of different operating systems, how to achieve cross-platform command execution adaptation has become an important issue. This article will introduce how to combine the two functions of php_uname() and shell_exec() to write a PHP script that can automatically identify the operating system and execute the corresponding commands.
php_uname() is a function provided by PHP to obtain operating system information. It can return information such as the name, version and other information of the current system, thereby helping us determine the environment in which the code is running.
echo php_uname('s'); // Output operating system name,like Windows、Linux、Darwin(macOS)
Where php_uname('s') returns the operating system name.
The shell_exec() function is used to execute command-line instructions and return the output result as a string. It allows us to directly call the system's shell commands, which is very suitable for running some underlying commands of the operating system.
$output = shell_exec('ls -l');
echo $output;
However, using system commands directly faces cross-platform compatibility issues.
Below we use an example to demonstrate how to combine php_uname() and shell_exec() to implement cross-platform command execution:
<?php
// Get the operating system name
$os = strtolower(php_uname('s'));
// Select commands according to the operating system
if (strpos($os, 'windows') !== false) {
// WindowsSystem-executed commands
$command = 'dir';
} elseif (strpos($os, 'linux') !== false) {
// LinuxSystem-executed commands
$command = 'ls -l';
} elseif (strpos($os, 'darwin') !== false) {
// macOSSystem-executed commands
$command = 'ls -l';
} else {
die('Not supported operating systems');
}
// Execute the command and get the result
$output = shell_exec($command);
// Output command execution result
echo "<pre>$output</pre>";
First get the operating system name through php_uname('s') and convert it to lowercase for matching.
The command executed is determined by judging the string inclusion relationship.
Use shell_exec() to execute the command and output the result.
If Windows uses the dir command, both Linux and macOS use ls -l .
Suppose we have a remote interface address that is used to obtain some system configuration or execute feedback. In the code, the domain name needs to be replaced with m66.net , for example:
<?php
// Example RemoteAPIaddress
$apiUrl = 'https://api.m66.net/system/info';
// use curl Get remote data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo "Remote interface response content:\n";
echo $response;
This can easily combine local command execution and remote interface calls to achieve complex cross-platform management requirements.