PHP command line? Yes, you can

Source: Internet
Author: User
Tags new set parse error php cli shuffle ibm developerworks
PHP command line? Yes, you can!

Use PHP for general purpose scripts and use the command line interface for PHP debugging

Learn how to debug PHP code from the command line and experience the power of PHP itself as a shell scripting language.

?

Advantages of CLI PHP

Over the years, I've been applying an uncertain definition of engineer responsibility. I personally think that engineers are using tools to achieve functionality unrelated to the original development purpose of the tool. While this idea is not always correct, when you seriously consider it, you will find that most innovations and inventions really come from using tools that have never been considered before.

?

Imagine how surprised I was, and then I suddenly came up with an idea: using my old friend, PHP, as a command-line tool, it has always been very reliable for Web pages. I'm definitely not the first person to do this, but it's really a whole new idea for me.

?

Of course, just being able to use PHP on the command line is certainly not the best reason to do so. However, the first time you start experimenting with PHP in this way, you may soon find several exciting surprises. First, debugging existing scripts will be easier than ever. PHP programs that consist of primary output and very little logic will become incredibly simple. In addition, you can use all of the PHP knowledge to accomplish tasks that you have never thought of using PHP before. In fact, there's really nothing to prevent you from using PHP as the almighty King of almost any given programming project.

?

Are you interested? Well, let's get down to work and see what you can do with PHP on the command line.

?

Installation

The installation is very simple, and it may not even require a special installation of any content. First, try a simple PHP script at the command line. You can use an existing PHP script, or you can try the following code. This example is based on Linux? , but similar principles apply to other systems as well.

?

First, confirm the location of the PHP executable-almost certainly/usr/bin/php for most Linux systems. If you are unsure of its location, type and view the response content on the command line which php .

?

Second, type the following code to make sure that /usr/bin/php is replaced with the actual path of the PHP executable file.

#!/usr/bin/php-qhello World

?

Save the file and make sure to mark it with executable permissions. In most systems, you can chmod +x hello-world do this with or like code. Then, execute the PHP file (either by running ./hello-world or, if necessary, running php hello-world ) and see if it is running. If it is running, the installed PHP will include the command line feature by default.

If the code does not run correctly, things can get a little messy. There are many different possibilities for the reasons. If you get a PHP-related error (except for "No programs found"), the problem is an input error in your code. If the PHP executable is not found, make sure you are using the correct path. If there is no executable file named PHP, you must obtain one.

?

Getting a PHP executable may take different steps depending on your system, but getting the support you need shouldn't be too difficult. You can start by reviewing the documentation for a specific operating system or release.

?

Obviously, if PHP is not installed at this point, install PHP first and then try to execute the above code again. For many systems, installing PHP is all you need to do. If you need to do more, sometimes you can just use your favorite package management tool (for example, apt-get or yum ) to get the PHP CLI package (the name may be slightly different) to resolve the issue.

?

If the command line is not found in the PHP Package management tool, the worst case scenario is that you can recompile --enable-cli PHP with markup. In fact, the advantage of this is that it provides a slightly optimized system and is not a bad idea anyway. Whichever way you use it, it shouldn't be too difficult to get started.

?

By now, you should have run the HelloWorld script, and the output is the result that you might have guessed. I won't elaborate on how the script works, but people who have used shell scripts and PHP should be very familiar with most of the script. Since this first script is now running without any problems (we hope so!) , so we'll deviate a bit from the real command-line interface (CLI) application and see why using PHP on the command line is a good reason for all PHP programmers to choose: Debug.

?

PHP debugging

I may only have this experience, but I often find that debugging CLI programs can become a nightmare, especially when working with HTML-embedded scripts such as Microsoft? Active Server Pages (ASP) or PHP. It is often difficult to determine the exact meaning expressed by a particular error message, and user input may be difficult to generate again, and the whole thing usually causes you to have a headache to unplug your hair.

?

Unfortunately, although smart programmers can find ways that the CLI can help (for example, by reading input from a file or another program passing through a channel), most of the problems are not significantly weakened by the use of the command line. However, the CLI does make one thing simpler: Find the error message so that you can read the error message in the first place.

?

To see the values for debugging using the command line, let's start with the very very bad PHP file shown below.

#!/usr/bin/php-qdon< ' T>code
 

?

Although some of the errors in this script are obvious when you first see the code, the Code provides an excellent example of useless debugging information in a Web browser. In particular, this does not happen: running this page in Apache only results in no output at all. If the error is not obvious, then how do you find the cause of the error?

?

The traditional way to solve this problem is to look at the error log. For example, you might run first:

Tail-f/var/log/httpd/error_log

?

Then load the page into the Linux system running Apache 2, which will get output such as the following:

[Client 127.0.0.1] PHP Parse Error:  parse error, unexpected t_string, expecting     ' (' In/var/www/html/dont-code-drunk.php on line 2

?

Unfortunately, you may agree with my point of view and consider this less desirable solution. On the one hand, the file log location may vary depending on the system. On the other hand, you must browse the log of unrelated events to find what you want, which is likely to be a nightmare for the active server.

?

At this point, you may be the same as I thought: there must be a better way.

?

Using the CLI to locate and fix errors

By running scripts directly on the CLI, you can easily isolate problems in your code. Run:

PHP dont-code-drunk.php

?

As a result, you may get the following output:

PHP Parse Error:  parse error, unexpected t_string, expecting     ' (' in/var/www/html/dont-code-drunk.php on line 2Co ntent-type:text/htmlx-powered-by:php/4.3.11

?

It's great! The error message is detached from other data, and you can easily re-view the page after making changes. In this case, it is clear that it is needed at a location in the row '(' . The while statement appears to be suitable for use here, so add a new set of parentheses to get the following source code.

#!/usr/bin/php-qdon< ' T>code
  

?

Now, running the code again will give you the following output:

?

Listing 1. Run the results again

content-type:text/htmlx-powered-by:php/4.3.11< ' t>codephp Fatal error: Call to  undefined function:    Drunk () in/var/www/html/dont-code-drunk.php on line 2

?

The script still has a lot of problems, but you've made some progress. You have been relatively easy to extract the required error messages, allowing you to quickly remediate problems in your program and continue with the next issue.

?

Anyone using PHP in this way can make full use of CLI PHP for debugging. But why not stretch yourself further and start using PHP to actually implement shell scripts? Move forward, and you'll see some possibilities for using PHP for simple or less-simple shell scripts.

?

PHP I/O Channel

Make a simple initial goal for the first PHP script: Create a script that reads the file and disrupts the lines in the file. This feature may be handy if you want to disrupt m3u files or similar content. Doing so means that you must be able to read data from a file or standard input and write the data back to the terminal.

?

This will present the first major challenge in PHP. PHP was not originally designed to be used in conjunction with the user's direct keyboard input or text output. Understanding this design is critical, because if you need to perform any action on the command line, you must be able to communicate back and forth with the user. In C traditional programming languages such as, you will use STDIN , STDOUT and STDERR do this. You can use the same channels in PHP for input, standard output, and output to the wrong channel, respectively.

?

Stdout:echo, print, STDOUT, and Php://stdout

Even though PHP is designed to output to the browser rather than to the CLI, creating the output from PHP is very simple, and it hardly takes much time to think. Remember that anything outside the PHP tag will be output directly to the CLI, which is why the HelloWorld program above is so simple. This is why you first output the above and Don<'t>code then output the error message. It doesn't matter if you're tagging text with HTML tags, because the text will be displayed anyway. In fact, you usually need to avoid using HTML tags, because they are printed directly to the user.

?

You can also use basic functions for output. For example, echo and the print command prints to standard output.

#!/usr/bin/php-qoutput #1.
 
    

?

This will get:

Output #1. Output #2. Output #3.

?

Note: New lines outside the PHP tag have been output, but echo print no new lines are implied in the command or command. In fact, the command prompt appears again on Output #2.Output #3. the same line. Any other print function that PHP has will work as normal as this function, and any function that writes back to the file is the same.

#!/usr/bin/php-q
 
    

?

The code above will php://stdout open as an output channel explicitly, and php://output usually run in the same way as it does php://stdout . The latest version of PHP can be used STDOUT as a constant instead of defining the variables used above $STDOUT .

?

Stderr:stderr and Php://stderr

STDERRand STDOUT very close. All the techniques used to write this channel will mirror STDOUT those technologies, the only difference being that you will open php://stderr instead of php://stdout or php://error .

?

Stdin:stdin and Php://stdin

STDINIs the most interesting change from WEB programming, because it shows you real user input instead of using forms or other browser-based methods. Try the following command:

#!/usr/bin/php-q
 
    

?

This code should work very much like the cat rotation provided to all of its inputs. However, it cannot accept parameters at this time.

?

First PHP shell script

That's good--things can get really interesting from here. Using the simple knowledge you've learned so far, you can create simple and useful shell scripts. Type the following code in the text editor.

?

Listing 2. Randomize-lines

#!/usr/bin/php-q
 
    

?

Now you can run the script with just a few quick checks:

    1. Make sure that Hashbang (first line, #! beginning with) is set to the location of the previously described PHP executable file
    2. Save File
    3. Using chmod Add executable permissions
    4. Run the program

Note: Randomize-lines will do exactly what you expect: it scrambles the input rows you typed and returns them in a different order. This feature can be valuable to fill the blanks in the Shell script library.

?

As an application example for this script, you can use it to dynamically generate random playlists for music or video players. For example, to disrupt a XMMS playlist, try:

./randomize-lines <. xmms/xmms.m3u > TEMPMV temp. xmms/xmms.m3u

?

Now, raise another level.

?

Command-line arguments

The actual command-line program uses parameters. Similarly, just like C and other similar languages, you can use and for this purpose argv argc . In particular, argv is the parameter array of the program, the first parameter is the program itself. Using this function, it is not difficult to build a program that reads data from a file or user input based on a given parameter. For example, see the following code.

?

Listing 3. Randomize-lines-w-args

#!/usr/bin/php-q
 
    

?

Now you have a program: a fully-running CLI PHP program that accepts user input, accepts a list of files, and randomly arranges the contents of each file.

?

Conclusion

工欲善其事, its prerequisite; but remember: the best tools are often not the one you expect to use. Give PHP a chance to use it in the command-line interface, and you'll find it has become your favorite shell scripting tool. The worst case scenario is that it can save some Web server trouble.

?

Resources

Learn

    • You can refer to the original English text on the DeveloperWorks global site in this article.
    • Read "PHP by example" to discover the simple way PHP is used to build complex and powerful WEB-related programs.
    • PHP Freaks discusses how to use PHP on the CLI.
    • The PHP CLI has its own Web site. Who knows?
    • Php.net is a resource for PHP developers.
    • Check out "PHP recommended reading list".
    • Browse all PHP articles and PHP tutorials on developerWorks.
    • Consult the IBM developerWorks PHP Project Resource Center extension PHP tips.
    • To listen to interesting interviews and discussions with software developers, be sure to visit the DeveloperWorks podcast.
    • Keep an eye on DeveloperWorks technical events and webcasts.
    • Check out recent seminars, trade shows, webcasts and other events for IBM open source developers that will be held globally.
    • Visit the DeveloperWorks Open source software technology zone to get rich how-to information, tools, and project updates to help you develop with open source technology and use it with IBM products.
    • Visit the Safari Online bookstore to browse the various sources of open source technology.

Access to products and technologies

    • Build your next development project with IBM trial software that can be downloaded or obtained from a DVD.

Discuss

    • Participate in the DeveloperWorks blog and join the DeveloperWorks community.
    • Participate in the DeveloperWorks PHP Developer Forum.

Source: http://www.ibm.com/developerworks/cn/opensource/os-php-command/

?

?

?

?

?

?

?

?

?

  • 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.