


PHP command line tools shell_exec, exec, passthru, system detailed usage introduction_PHP tutorial
All of these commands spawn a child process that runs the command or script you specify, and each child process captures the command output as it is written to standard output (stdout).
shell_exec()
The shell_exec() command line is really just a variation of the backtick (`) operator. If you've ever written a shell or Perl script, you know that you can capture the output of other commands inside the backtick operator. For example, Listing 1 shows how to use backticks to get the word count for each text (.txt) in the current directory.
Listing 1. Counting the number of words using backticks
#! /bin/sh
number_of_words=`wc -w *.txt`
echo $number_of_words
#result would be something like:
#165 readme.txt 388 results.txt 588 summary .txt
#and so on....
In your PHP script you can run this simple command in shell_exec() as shown in Listing 2 and get desired result. It is assumed here that there are some text files in the same directory.
Listing 2. Running the same command in shell_exec()
$results = shell_exec('wc -w *.txt');
echo $results;
?>
You can see it in Figure 1 , the results obtained are the same as those obtained from the shell script. This is because shell_exec() allows you to run an external program through the shell and then returns the result as a string.
Figure 1. Results of running a shell command via shell_exec()

Note that just using the trailing apostrophe operator will give you the same result, as shown below.
Listing 3. Using only the trailing apostrophe operator
$results = `wc -w *.txt`;
echo $results;
?>
Listing 4 gives a simpler method.
Listing 4. A simpler method
echo `wc -w *.txt`;
?>
It is important to know that a lot can be done through the UNIX command line and shell scripts. For example, you can use pipes to connect commands. You can even create a shell script within it using operators and just call the shell script (with or without parameters as needed).
For example, if you only want to count the words of the first 5 text files in that directory, you can use a vertical bar (|) to connect the wc and head commands. Alternatively, you can place the output inside a pre tag to render it more beautifully in a web browser, as shown below.
Listing 5. More complex shell commands
$results = shell_exec('wc -w *.txt | head -5');
echo "
".$results . "
"; ?>
Figure 2 demonstrates the results of running the script in Listing 5.
Figure 2. Results from shell_exec() running a more complex shell command

Later in this article, you will learn how to pass arguments to these scripts using PHP. Now you can think of this as a way to run a shell command, but remember that you can only see standard output. If an error occurs with a command or script, you won't see the standard error (stderr) unless you add it to stdout via a pipe.
passthru()
passthru() allows you to run external programs and display the results on the screen. You don't need to use echo or return to see the results; they will be displayed on the browser. You can add optional parameters, which are variables that hold the code returned from the external program, such as 0 for success, which provides a better mechanism for debugging.
In Listing 6, I use the passthru() command to run the word counting script I ran in the previous section. As you can see, I also added a $returnval variable that contains the return code.
Listing 6. Use the passthru() command to run the word counting script
passthru('wc -w *.txt | head -5',$returnval);
echo "
".$returnval;
?>
Note that I don't need to use echo to return anything. The results are displayed directly on the screen as shown below.
Figure 3. The result of running the passthru() command using the return code

In Listing 7, I introduced a small error by removing the dash (-) in front of the 5 in the header of the script .
Listing 7. Introducing a bug in the word count script
//we introduce an error below (removing - from the head command)
passthru('wc -w *.txt | head 5',$returnval);
echo "
".$returnval;
?>
Note that the script does not run as expected. What you get is a blank screen, a horizontal line, and a return value of 1, as shown in Figure 4. This return code usually indicates that some error occurred. Finding and fixing bugs is much easier if you can test the return code.
Figure 4. View error code when using passthru()

exec()
The exec() command is similar to shell_exec(), except that it Returns the last line of output and optionally populates the array with the command's complete output and error code. Listing 8 shows what happens when you run exec() without capturing the data in the data array.
Listing 8. Running exec() without capturing data in the data array
$results = exec('wc -w *.txt | head -5');
echo $results;
#would print out just the last line or results, i.e.:
#3847 myfile.txt
?>
To capture the results in an array, add the name of the array as the second argument to exec(). I performed this step in Listing 9, using $data as the name of the array.
Listing 9. Capturing the results of the data array from exec()
php
$results = exec('wc -w *.txt | head -5',$data);
print_r($data);
#would print out the data array:
# Array ([0]=> 555 text1.txt [1] => 283 text2.txt)
?>
After capturing the results in the array, you can Do some processing. For example, you can divide at the first space, store separated values in a database table, or apply specific formatting or tags to each row.
system()
As shown in Listing 10, the system() command is a hybrid. It directly outputs whatever it receives from the external program, just like passthru(). It also returns the last line like exec() and makes the return code available.
Listing 10. system() command
system('wc -w *.txt | head -5');
#would print out:
#123 file1.txt 332 file2.txt 444 file3.txt
#and so on
?>
Some examples
Now that you know how to use these PHP commands, you may still have some questions. For example, when should I use which command? It all depends on your needs.
Mostly I use exec() commands and data arrays for everything. Or use shell_exec() for simpler commands, especially if you don't care about the results. If I just need to return a shell script, I use passthru(). Often I use different functions on different occasions, and sometimes they are interchangeable. It all depends on my mood and what I'm trying to achieve.
Another question you might ask is “What are their strengths?”. If you have no clue, or have a project that would be great for using shell commands but don't know how to use them, I'm here to provide some insight.
If you are writing an application that provides various backup or file transfer functionality, you may choose to run an rsync-supported shell script using shell_exec() or one of the other commands provided here. You can write a shell script to include the necessary rsync commands and then use passthru() to execute it based on a user's command or a cron job.
For example, a user with appropriate permissions in your application (such as admin rights) wants to send 50 PDF files from one server to another. The user then needs to navigate to the correct location in the application, click Transfer, select the PDF that needs to be sent, and click Submit. Along the way, the form should have a PHP script that runs the rsync script via passthru() using the return options variable as shown below.
Listing 11. Sample PHP script to run rsync script through passthru()
< ;?php
passthru('xfer_rsync.sh',$returnvalue);
if ($returnvalue != 0){
//we have a problem!
//add error code here
}else{
//we are okay
//redirect to some other page
}
?>
If your application needs to list processes or files, or data about those processes or files, you can easily accomplish this using one of the commands summarized in this article. For example, a simple grep command can help you find files that match specific search criteria. Using it with the exec() command saves the results into an array, which allows you to build an HTML table or form, which in turn allows you to run other commands.
So far, I've discussed user-generated events - whenever the user presses a button or clicks a link, PHP runs the corresponding script. You can also use standalone PHP scripts with cron or other schedulers to achieve some interesting effects. For example, if you have a backup script, you can run it via cron, or package it into a PHP script and run it. Why do this? This seems redundant, doesn't it? That's not the case - you need to think of it this way, you can run the backup script via exec() or passthru() and then perform some behavior based on the return code. If an error occurs, you can log it to the error log or database, or send a warning email. If the script succeeds, you can dump the raw output to a database (for example, rsync has a verbose mode, which is useful for diagnosing problems later).
-------------------------------------------------- ------------------------------------
Security
Let’s briefly discuss security here Sex: If you accept user input and pass the information to the shell, it's better to filter the user input. Remove commands you consider harmful and disallowed, such as sudo (run as superuser) or rm (remove). In fact, you probably don't want the user to send an open request, but instead let them choose from a list.
For example, if you run a transfer program that accepts a list of files as an argument, you should list all the files via a series of checkboxes. Users can select and deselect files and activate the rsync shell script by clicking Submit. Users cannot enter files themselves or use regular expressions.
-------------------------------------------------- ------------------------------------
Conclusion
In this article, I demonstrated Basics of running shell scripts and other commands using PHP commands. These PHP commands include shell_exec(), exec(), passthru(), and system(). Now, you should put what you learned into practice in your own application.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software