PHP function shell_exec: executing an external command

Almost all programming languages ​​include the ability to run external code or shell commands of the operating system. The presence of such an opportunity is considered the rule of decency and full functionality of the language. Using this feature is considered a security risk and the lack of full functionality of an application written in this language.

PHP provides the programmer with the ability to run an external command and provides the transfer of the results of the run to a variable in the form of text.

Operating environment and external team

The choice is not particularly large, but the variety of options can be confusing. If the server running PHP is running Windows, then there will be no special unforeseen situations. In the Linux family, various uncertainties are possible.

Running external code




In any case, running external code is a threat. Therefore, the use of the PHP feature shell_exec () is a thoughtful and balanced decision.

Typically, the purpose of using this feature is to periodically launch an external application that collects information and moves it to the folders of the web resource. Often used to run external code to transmit statistics of the site, financial report, etc.





There are a lot of options when managing from a web resource requires "external assistance", but it is preferable when any contact with the "external environment" is executed "on its own" without using PHP shell_exec ().

Syntax and Usage Logic

External code is called by assigning the result of the call to shell_exec () to a variable.

PHP shell_exec examples




In this case, apache & PHP are installed on a working computer with Windows 10. Immediately, there were problems with the Cyrillic alphabet and the mismatch between the output streams of the command from the operating system and the usual stream perceived by the browser was obvious.

To correctly display the output, you need to analyze the operation of shell_exec (). In PHP, testing examples should be as rigorous as possible to achieve safe use.

Safe use




Any operating system allows the formation of a command line when several commands are written in one line at once. The shell_exec function allows the use of such a command line.

In all cases of application of the function, a set of test cases should be provided on which to check the security of using access to the operating system.




All Articles