SoFunction
Updated on 2025-03-10

Methods for executing cmd commands in PHP

This article introduces the method of executing the cmd command in the php code, and introduces the method of configuring the safe_mode parameter in the file to support command execution. For those who need it, please refer to it.

illustrate:
This section is implemented in the environment where the wamp package is installed.

First, turn on and turn off safe mode safe_mode = off, and then take a look at the disable function list disable_functions = proc_open, popen, exec, system, shell_exec, and remove exec.
php code:

Copy the codeThe code is as follows:

<?php
exec("mkdir d:\\test",$out);
print_r($out);
?>

Execute the php file and you will find that there is an additional test folder under the d disk.

Reference documentation:

Exec function analysis
exec syntax: string exec(string command, string [array], int [return_var]);
exec return value: string

Exec parameter description
Command – Commands that need to be executed
Array – is the output value
return_var – is the return value 0 or 1. If 0 is returned, the execution will be successful, and if 1 is returned, the execution will be failed.
Exec is not successful, debugging solution

Tips sharing:

Using the pipeline command, using 2>&1, the command will output the errors during shell execution to the $output variable, and output the variable to analyze.

For example:

exec(‘convert ', $output, $return_val);
Modified to:

Copy the codeThe code is as follows:

exec(‘convert 2>&1′, $output, $return_val);
print_r($output);