Introduction: PHP executes external commands on linux (sorting)

Source: Internet
Author: User
To call external commands in PHP, you can use, 1 & gt; to call specialized functions, 2 & gt; reverse quotation marks, 3 & gt; popen () to open the process, three methods to implement directories: 1. Introduction to calling external commands in PHP
II. security issues
III. timeout
IV. problems with running commands in the linux environment in PHP


1. Introduction to calling external commands in PHP
To call external commands in PHP, you can use, 1> call special functions, 2> reverse quotation marks, 3> popen () function to open the process. three methods are provided:
 
Method 1: use the special functions provided by PHP (four ):
PHP provides four specialized functions for executing external commands: exec (), system (), passthru (), shell_exec ()
1) exec ()
Prototype: string exec (string $ command [, array & $ output [, int & $ return_var])
Note: exec does not output results when executing system external commands, but returns the last line of results. If you want to get the result, you can use the second parameter to output it to the specified array. A record in this array represents the output row. That is, if there are 20 rows of output results, this array will have 20 records, so if you need to repeatedly output the results of calling different system external commands, it is best to clear this array unset ($ output) when outputting the results of each system external command to prevent confusion. The third parameter is used to obtain the status code for command execution. generally, 0 is returned for successful execution.
Exec ("dir", $ output );
Print_r ($ output );
?>
 
2) system ()
Prototype: string system (string $ command [, int & $ return_var])
Note: the difference between system and exec is that when system executes an external command of the system, it executes the given command, and outputs and returns the result. The second parameter is optional and is used to obtain the status code after the command is executed.
System ("pwd", $ result );
Print $ result; // status code of the output command
?>
A brief introduction to the status code of the second parameter result:
If 0 is returned,
In Bash, when an error occurs in a fatal signal, bash returns the 128 + signal number as the return value.
If the command cannot be found, 127 is returned.
If the command is found but cannot be executed, 126 is returned.
Bash itself returns the return value of the last command.
If an error occurs during execution, a non-zero value is returned.
Fatal Signal: 128 + signo
Can't not find command: 127
Can't not execute: 126
Shell script successfully executed: return the last command exit status
Fatal during execution: return non-zero

 
3) passthru ()
Prototype: void passthru (string $ command [, int & $ return_var])
Note: the difference between passthru and system is that passthru directly outputs the result to the browser without returning any value and can output binary data like data. The second parameter is an optional status code.
Header ("Content-type: image/gif ");
Passthru ("/usr/bin/ppm2tiff/usr/share/tk8.4/demos/images/teapot. ppm ");
?>
 
4) shell_exec ()
Prototype: string shell_exec (string $ cmd)
Note: run the command $ cmd directly.
$ Output = shell_exec ('ls-lart ');
Echo"
$output
";
?>
 
Method 2: Anti-apostrophes
Prototype: Anti-apostrophes (and ~ Execute system external commands with the same key.
Note: When using this method to execute system external commands, make sure that the shell_exec function is available. Otherwise, the system external commands cannot be executed using this reverse code.
Echo 'dir ';
?>
 
Method 3: Use the popen () function to open a process
Prototype: resource popen (string $ command, string $ mode)
Description: it can interact with commands. The method described earlier can only execute commands, but cannot interact with commands. Sometimes you have to enter something into the command. for example, when adding a system user, you need to call su to change the current user to the root user. The su command must enter the root password on the command line. In this case, the method mentioned previously cannot be used.
The popen () function opens a Process Pipeline to execute a given command and returns a file handle that can be read and written to it. Returns a file pointer like the fopen () function. Unless you use a single mode to open (read or write), you must use the pclose () function to close it. This pointer can be called by fgets (), fgetss (), and fwrite. If an error occurs, FALSE is returned.
Error_reporting (E_ALL );
 
/* Add redirection so we can get stderr .*/
$ Handle = popen ('/path/to/executable 2> & 1', 'r ');
Echo "'$ handle';". gettype ($ handle). "\ n ";
$ Read = fread ($ handle, 2096 );
Echo $ read;
Pclose ($ handle );
?>
II. security issues:

Since PHP is basically used for WEB program development, security has become an important aspect of consideration.
As a result, PHP designers added a security mode to PHP.
Set safe_mode = On in php. ini.
If running in safe mode, the PHP script will be subject to the following four restrictions:
Execute external commands
Restrictions on opening a file
Connect to the MySQL database
HTTP-based authentication

In security mode, only external programs in a specific directory can be executed, and calls to other programs will be rejected. This directory can be specified by using the safe_mode_exec_dir command in the php. ini file, or by adding the-with-exec-dir option to compile PHP. the default value is/usr/local/php/bin.

When you use these functions to execute system commands, you can use the escapeshellcmd () and escapeshellarg () functions to prevent users from maliciously executing commands on the system. escapeshellcmd () the command is executed, while the escapeshellarg () parameter is used to execute the system command. These two parameters are similar to the addslashes () function.

III. timeout
When the returned results of executing commands are very large, you can consider outputting the returned results to other files and then reading the files separately, which can significantly improve the efficiency of program execution.
If the command to be executed takes a long time, put the command in the background of the system to run it. However, by default, functions such as system () will not be returned until the command is run (in fact, the output result of the command is waiting), which will definitely cause the PHP script to time out. The solution is to redirect the command output to another file or stream, for example:
System ("/usr/local/bin/order_proc>/tmp/abc ");
?>

However, it takes several minutes for me to call the dos command. in order to make batch processing unable to simply write the result into the file, we need to execute the following programs in sequence.
PHP sets the time limit for calling system commands. if the call times out, although the command will still be executed, PHP does not get the returned value and is terminated (the most hateful thing is, no error is displayed)
Modify php. ini and restart Apache to allow system commands to run for a longer time
Max_execution_time= 600

IV. problems with running commands in the linux environment in PHP
Php is generally executed as an apache user. it may also be a www user. Add apache to the parent folder group that stores your files, and set the parent folder permission to 775, in this way, members of the group have the write permission, and apache can rewrite the permissions of all files in the directory if they belong to this group.
For example: chown www: www dirName
In this way, the dirName directory can be controlled by php.
Note: Changing the apache/php running user method is not safe.

In addition, even if the file or directory is already www, php's security settings are taken care of, and some linux installation commands may still fail to run, such as the ffmpeg software I have installed, this is because of the linux running Permission problem. even if ffmpeg has www permission settings, the library files on which ffmpeg depends are not allowed to run by www users, therefore, php still reports 127 or 126 errors when running this program. you can run the ldd command to view the library information on which the ffmpeg command depends.
In this case, you must configure the ffmpeg dependency Library. The specific method is a topic in linux management. I will not discuss it here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.