Home Backend Development PHP Tutorial Using command line tools in PHP_PHP Tutorial

Using command line tools in PHP_PHP Tutorial

Jul 13, 2016 pm 05:38 PM
php web use create Discover Command Line exist tool you characteristic of

If you have used PHP, you will find that it is an excellent tool for creating feature-rich web pages. As a major scripting language, PHP:

·Easy to learn.

There are many powerful frameworks (such as CakePHP and CodeIgniter) that allow you to be as productive as a Rails programmer.

 ·Ability to communicate with MySQL, PostgreSQL, Microsoft SQL Server, and even Oracle.

·Ability to easily integrate with JavaScript frameworks such as script.aculo.us and jQuery.

But sometimes, you want to do more, or have to do more. What I mean is that you have to deal directly with the file system of the server where PHP is running. You will eventually need to work with files on the file system, learn about running processes, or perform other tasks.

 First, you are satisfied with opening files in PHP using the file() command. But at some point, the only way to accomplish something is to run a shell command on the server and get a specific output. For example, you might want to know how many files a specific directory contains. Or you want to know how many lines were written to a certain set of log files. Or you want to manipulate the files, copy them to another directory, or use rsync to send them to another location.

 In the article "PHP Command line? Yes, you can!" Roger McCoy demonstrates how to use PHP - No web browser required. In this post, I look at the same topic from another angle, showing you how to tightly integrate with the underlying shell commands and include return values ​​into your interface and processes. These operations only work if you are running on Linux, Berkeley Software Distribution (BSD), or some other UNIX version. I'm assuming you're running on the Linux-Apache-MySQL-

PHP

(LAMP) stack. If you are running another version of UNIX, the specific details may be different because the availability of the command line is different in each version. I know many people are still developing on Mac OS X (running some version of BSD), so I tried to keep the example commands generic to ensure easy portability.

 

Command line overview  

PHP

Command Line Interface (CLI) Server Application Programming Interface (SAPI) was released in PHP V4.2.0 for experimental purposes. As of V4.3.0, it is fully supported and enabled by default. The PHP CLI SAPI allows you to develop PHP supported shell scripts, even desktop-based scripts. In fact, it is possible to use PHP to create tools that can be run directly from the command line. This way, PHP developers can be as productive as Perl, AWK, Ruby or shell programmers.  This article explores the tools built into

PHP

to let you understand the underlying shell environment and file system in which PHP runs. PHP provides a number of functions for executing external commands, including shell_exec(), exec(), passthru() and system(). These commands are similar but provide different interfaces for external programs you run. All these commands spawn a child process for running the command or script you specify, and each child process will write the command output to standard output ( stdout).  

shell_exec()

 shell_exec() The

command

line is actually 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 words using backticks

 #!/bin/sh

Number_of_words=`wc -w *.txt`

echo $number_of_words

 #result would be something like:

 #165readme.txt 388results.txt 588summary.txt

 #andso on....

In your

PHP

script, you can run this simple command in shell_exec(), as shown in Listing 2, and get the desired results. 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;

?> $results =shell_exec(wc -w *.txt);

echo $results;

 >

As you can see 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. The result of running the shell command through 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;

?> $results =`wc -w *.txt`;

echo $results;

 >

Listing 4 shows a simpler approach.

List 4. A simpler method

 

echo `wc -w *.txt`;

?> echo `wc -w *.txt`;

 >

It’s important to know that a lot can be done with the UNIX command line and shell scripts. For example, you can use pipes to connect commands. You can even create a shell script in it using operators and just call the shell script (with or without arguments as needed).

For example, if you only want to count the number of words in the first 5 text files in the 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

 

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486464.htmlTechArticleIf you have used PHP, you will find that it is an excellent tool for creating feature-rich Web pages. As a major scripting language, PHP: Easy to learn. There are many powerful frameworks (such as...

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
How to measure thread performance in C? How to measure thread performance in C? Apr 28, 2025 pm 10:21 PM

Measuring thread performance in C can use the timing tools, performance analysis tools, and custom timers in the standard library. 1. Use the library to measure execution time. 2. Use gprof for performance analysis. The steps include adding the -pg option during compilation, running the program to generate a gmon.out file, and generating a performance report. 3. Use Valgrind's Callgrind module to perform more detailed analysis. The steps include running the program to generate the callgrind.out file and viewing the results using kcachegrind. 4. Custom timers can flexibly measure the execution time of a specific code segment. These methods help to fully understand thread performance and optimize code.

How to use the chrono library in C? How to use the chrono library in C? Apr 28, 2025 pm 10:18 PM

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

How to use string streams in C? How to use string streams in C? Apr 28, 2025 pm 09:12 PM

The main steps and precautions for using string streams in C are as follows: 1. Create an output string stream and convert data, such as converting integers into strings. 2. Apply to serialization of complex data structures, such as converting vector into strings. 3. Pay attention to performance issues and avoid frequent use of string streams when processing large amounts of data. You can consider using the append method of std::string. 4. Pay attention to memory management and avoid frequent creation and destruction of string stream objects. You can reuse or use std::stringstream.

How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

How to optimize code How to optimize code Apr 28, 2025 pm 10:27 PM

C code optimization can be achieved through the following strategies: 1. Manually manage memory for optimization use; 2. Write code that complies with compiler optimization rules; 3. Select appropriate algorithms and data structures; 4. Use inline functions to reduce call overhead; 5. Apply template metaprogramming to optimize at compile time; 6. Avoid unnecessary copying, use moving semantics and reference parameters; 7. Use const correctly to help compiler optimization; 8. Select appropriate data structures, such as std::vector.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

See all articles