How PHP executes external commands on Linux

Source: Internet
Author: User
This article mainly introduces PHP in the implementation of the external command on Linux method, interested in the friend's reference, I hope to be helpful to everyone.


First, the introduction of calling external commands in PHP
Ii. on security issues
Third, about the time-out problem
Iv. problems with commands in PHP running Linux environment

First, the introduction of calling external commands in PHP

Call the external command in PHP, you can use,1> call special functions, 2>, 3>popen () function open process, three ways to achieve:

Method One: Special functions provided by PHP (four):

PHP provides 4 specialized functions for executing external commands: EXEC (), System (), PassThru (), Shell_exec ()

1) EXEC ()

Prototype: string exec (String $command [, Array & $output [, int & $return _var])

Description: Exec executes the system external command without outputting the result, but instead returns the last line of the result. If you want a result, you can use the second argument to output it to the specified array. This array one record represents the output row. That is, if the output has 20 rows, then this array will have 20 records, so if you need to repeatedly output the results of invoking different system external commands, it is best to empty the array unset ($output) when outputting the result of each system external command, in case of confusion. The third parameter is used to get the status code for the execution of the command, and usually the success is returned 0.

<?php  exec ("dir", $output);  Print_r ($output);? >

2) System ()

Prototype: String System (String $command [, int & $return _var])

Description: The difference between system and exec is that the system executes a given command, outputs, and returns the results when it executes an external command on the systems. The second parameter is optional and is used to get the status code after the command executes.

<?phpsystem ("pwd", $result);p rint $result;//output command result status code?>

For a brief introduction to the second parameter result status code:

If return 0 is a successful run,

In bash, when an error occurs on a fatal signal, BASH returns 128+signal number as the return value.

If the command is not found, 127 will be returned.

If the command is found, but the command is not executable, 126 is returned.

In addition, bash itself returns the return value of the last instruction.

If an error occurs in execution, a nonzero 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])

Description: The difference between PassThru and system, passthru directly outputs the result to the viewer, does not return any values, and it can output binary, image-like data. The second parameter is optional and is the status code.

<?phpheader ("Content-type:image/gif");p assthru ("/usr/bin/ppm2tiff/usr/share/tk8.4/demos/images/teapot.ppm") ;? >

4) Shell_exec ()

Prototype: String Shell_exec (String $cmd)

Description: Execute command $cmd directly

<?php$output = shell_exec (' Ls-lart '); echo "<pre> $output </pre>";? >

Method Two: Anti-apostrophe

Prototype: Reverse apostrophe ' (and ~ in the same key) Execute system external command

Note: When you use 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 type of anti-apostrophe.

<?php  Echo ' dir ';? >

Method Three: Open the process with the Popen () function

Prototype: Resource Popen (String $command, String $mode)

Description: Ability to interact with commands. The method described earlier can only simply execute commands, but cannot interact with commands. Sometimes you have to enter something into the command, such as adding a system user, to call su to switch the current user to the root user, and the SU command to enter the root password on the command line. In this case, it is obviously not possible to use the method mentioned earlier.

The Popen () function opens a process pipeline to execute a given command, returns a file handle, and can read and write to it. The return value is the same as the fopen () function, which returns a file pointer. Unless you are using a single mode to open (read or write), you must use the Pclose () function to close. The pointer can be called by fgets (), FGETSS (), fwrite (). When an error occurs, returns FALSE.

<?phperror_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;p close ($handle); >

Ii. on security issues:

Because PHP is basically used for Web program development, security has become an important aspect of people's thinking.

So PHP's designers have added a door to PHP: Safe mode.

Settings in php.ini Safe_mode = On

If you are running in Safe mode, then the PHP script will be subject to the following four limitations:

Execute external command
There are some limitations when opening a file
Connect to MySQL Database
HTTP-based Authentication

In safe mode, only external programs in a particular directory can be executed, and calls to other programs will be rejected. This directory can be specified in the php.ini file with the Safe_mode_exec_dir directive, or in the compiler PHP is added –with-exec-dir option, the default is/usr/local/php/bin.

When you use these functions to execute system commands, you can use the Escapeshellcmd () and Escapeshellarg () functions to prevent the user from maliciously executing commands on the system, Escapeshellcmd () for the executed system commands, The Escapeshellarg () is for parameters that execute system commands. These two parameters are somewhat similar to the functionality of Addslashes ().

Third, about the time-out problem

When the result of the execution of a command is very large, you may want to consider outputting the returned result to another file, and then read the file separately, which can significantly improve the efficiency of program execution.

If the command to be executed takes a long time, then the command should be placed in the background of the system to run. However, by default, functions like system () wait until the command finishes running to return (in effect, the output of the command), which will definitely cause the PHP script to time out. The workaround is to redirect the output of the command to another file or stream, such as:

<?phpsystem ("/usr/local/bin/order_proc >/tmp/abc");? >

But I call the DOS command takes a few minutes, and in order to batch processing can not simply write the results to the file, order to execute the following program

PHP sets the time limit for invoking system commands, and if the call command times out, the command is still executed, but PHP does not get the return value and is terminated (most hateful, no error is displayed)

Modify php.ini and restart Apache to allow system commands to run for a longer period of time

Max_execution_time = 600

Iv. problems with commands in PHP running Linux environment

PHP is generally performed as Apache users, or it may be WWW users, to add Apache to the storage of your files in the parent folder belonging to the group, and then change the permissions of the parent folder is 775, so that members of the group have write permissions, Apache belongs to this group and can overwrite all the files in that directory.

Example: Chown www:www dirName

So that the DirName directory can be controlled by PHP

Note: Changing the apache/php user method is not secure

In addition, even if the file or directory is already www,php security settings are also taken care of, some of their own installation of Linux command may not be able to run, such as I have installed the FFmpeg software, because of Linux operation permissions problem, even if FFmpeg has the WWW permission settings, However, since FFmpeg depends on the library file is not allowed to run WWW users, so php run this program will still report 127 or 126 errors, through the LDD command can see the ffmpeg command depends on the library situation.

At this point, you must set the FFmpeg dependency library on line. The specific method belongs to the topic of Linux management, which is not discussed here.

The above is the whole content of this article, I hope that everyone's study has helped.

Related Article

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: 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.