First of all, I would like to introduce PHP to execute the Linux system commands several basic functions. For a long time I have been confused about the specific usage differences of the following functions.
system function
Description: Execute external program and display output data.
Syntax: string system (String command, int [Return_var]);
return value: String
Detailed Introduction:
This function is like the function system () in C, which executes the instruction and outputs the result. If the Return_var parameter exists, the state after executing the command is filled in the Return_var. Also noteworthy is that if you need to deal with user input data, but also to prevent users to cheat the system, you can use Escapeshellcmd (). If PHP is executed in a modular form, this function automatically updates the output buffer registers of the WEB server after each row output. You can use PassThru () If you need a complete return string and you do not want to go through unnecessary other intermediate output interfaces.
Instance code:
< php
$last _line = System (' ls ', $retval);
Echo ' last line of the output: '. $last _line;
Echo ' ?>
exec function
Description: Perform external programs.
Syntax: string exec (String command, string [array], int [return_var]);
return value: String
Detailed Introduction:
This function executes an external program or an external instruction that enters the command. Its return string is only the last line returned after the execution of the external program, and you can use the PassThru () function if you need a full return string.
If the parameter array exists, the command adds the array to the parameter and, if the array is not processed, call unset () before executing exec (). If the Return_var and array two parameters exist, the state after the command execution is filled in the Return_var.
It is worth noting that if you need to deal with user input information, but also to prevent users from playing tricks to crack the system, you can use Escapeshellcmd ().
Instance code:
<?php
echo exec (' whoami ');
?>
Popen function
Description: Open the file.
Syntax: int popen (String command, string mode);
return value: Integer
Detailed Introduction:
This function executes an instruction file that is processed by pipe. Files opened with this function can only be one-way (read-only or write-only), and must be closed with pclose (). You can use Fgets (), FGETSS () and fputs () on file operations. Returns a value of False if an error occurs in the open file.
Instance code:
;?
$fp = Popen ("/bin/ls", "R");
?>