search
HomeBackend DevelopmentPHP TutorialUsing command line tools in PHP_PHP Tutorial

Using command line tools in PHP_PHP Tutorial

Jul 13, 2016 pm 05:38 PM
phpwebusecreateDiscoverCommand Lineexisttoolyoucharacteristicof

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

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: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

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 and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

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 and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

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.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

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

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

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.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft