PHP has a wide range of capabilities, including the ability to execute Linux commands directly from PHP scripts. This functionality allows PHP developers to interact with the underlying operating system, execute system commands, and retrieve the output for further processing.In this article, we will explore different methods and examples of executing Linux commands from PHP.

 php exec linux commands


Using the exec() Function:

The `exec()` function in PHP allows you to execute Linux commands and retrieve the output. Here's a simple example:

//...

$command = 'ls -l';
$output = exec($command);
echo $output;

//...

In this example, the `ls -l` command is executed, and the output is stored in the `$output` variable. Finally, the output is displayed using the `echo` statement.

Using the shell_exec() Function:

The `shell_exec()` function is another option for executing Linux commands from PHP. It returns the complete output as a string. Here's an example:

//...

$command = 'cat /etc/passwd';
$output = shell_exec($command);
echo $output;

//...

In this example, the `cat /etc/passwd` command is executed, and the contents of the `/etc/passwd` file are stored in the `$output` variable. The output is then displayed using the `echo` statement.

Using the passthru() Function:

The `passthru()` function is useful when you want to execute a command and display the output directly without storing it in a variable. Here's an example:

//...

$command = 'ping -c 5 google.com';
passthru($command);

//..

In this example, the `ping -c 5 google.com` command is executed, and the output is directly passed through to the browser.

Using the system() Function:

The `system()` function is similar to `exec()`, but it displays the output directly instead of returning it as a string. Here's an example:

//..

$command = 'uname -a';
system($command);

//...

In this example, the `uname -a` command is executed, and the output is displayed in the browser.

Using backticks:

PHP also allows you to execute Linux commands using backticks. Here's an example:

//...

$command = `df -h`;
echo $command;

//...

In this example, the `df -h` command is executed, and the output is stored in the `$command` variable. Finally, the output is displayed using the `echo` statement.

It is important to note that executing Linux commands from PHP can have security implications. You should sanitize and validate user input before executing any commands to prevent command injection vulnerabilities.

In conclusion, PHP provides several methods to execute Linux commands from within your scripts. The `exec()`, `shell_exec()`, `passthru()`, `system()`, and backticks are all effective ways to interact with the underlying operating system. However, be cautious when executing commands and ensure proper input validation to mitigate security risks.