Php Command Line tool shell_exec, exec, passthru

Source: Internet
Author: User

PHP provides functions for executing external commands, including shell_exec (), exec (), passthru (), system ().

 

1. shell_exec ()

The command line is actually only a variant of the suffix marker (') operator. Returns the output after the command is executed.

For example, the following command shows how to obtain the list of files under the/usr file in the current directory by using the reverse marker.

A) Shell-based scripts

#! /Bin/sh
Ls/usr

 

B) calls in PHPShell_exec (), Run the same command

<? Php <br/> $ lists = shell_exec ('ls/usr'); <br/> echo $ lists; <br/>?> 

 

2. passthru ()

Allows you to run external programs and display results on the screen.

You do not need to use echo or return to view the results. It will directly output the results to the browser (or the current terminal ).

You can add an optional parameter, that is, the variable that saves the code returned from an external program, for example, 0 indicating success, which provides a better mechanism for debugging.

<? Php <br/> passthru ('ls/usr | head-5', $ returnval); <br/> if ($ returnval) {// $ returnval> 1, an error occurs. <br/> echo 'script error'; <br/>} else {<br/> echo 'Directory listing completed '; <br/>}< br/>?> 

 

3. Exec ()

The Exec () command is similar to the shell_exec () command. The difference is that it returns the last line of the output, and can be used to populate the array with the complete output and error code of the command.

A)RunExec ()Without capturing data in the data array

<? Php <br/> $ Results = exec ('ls/usr | head-5'); <br/> echo $ results; <br/> // only output the result of the last row <br/>?> 

 

B)SlaveExec ()Capture the results of the data array

<? Php <br/> $ Results = exec ('ls/usr | head-5', $ data); <br/> print_r ($ data ); </P> <p> // The returned data array format <br/> // The format is as follows: <br/> // array ([0] => test [1] => Local/) <br/>?> 


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.