PHP command line? Yes, you can

Source: Internet
Author: User
Tags php cli ibm developerworks
PHP command line? Yes, you can! Use PHP scripts for general purposes and the command line interface for PHP debugging to learn how to Debug PHP code through the command line, and to experience the power of PHP as a shell scripting language .? CLIPHP has been applying uncertain engineer responsibility definitions for many years. My PHP command line? Yes, you can!

Use PHP scripts for general purposes and the command line interface for PHP Debugging

Learn how to Debug PHP code through command lines and experience the power of PHP as a shell script language.

? Advantages of CLI PHP

For many years, I have been applying uncertain engineer responsibility definitions. I personally think that engineers use tools to implement functions unrelated to the original development purpose of the tool. Although this idea is not always correct, when you think about it seriously, you will find that most innovations and inventions do 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 am definitely not the first person to do this, but this is indeed a brand new idea for me.

?

Of course, it's justYesUsing PHP in the command line is certainly not the best reason for doing so. However, when you start experimenting with PHP in this way for the first time, you may soon find several exciting surprises. First, debugging existing scripts will become simpler than ever. PHP programs consisting of major outputs and few logics will become incredibly simple. In addition, you can use all the PHP knowledge to complete tasks that have never been completed before using PHP. In fact, there is really nothing to prevent you from using PHP as the full power of almost all given programming projects.

?

Interested? Well, let's get started and see what tasks you can use PHP in the command line.

? Install

Installation is very simple, and it may not even require any special installation. First, try a simple PHP script in the command line. You can use an existing PHP script or try the following code. This example is based on Linux? But similar principles apply to other systems.

?

First, confirm the location of the PHP executable file-for most Linux systems, it is almost certainly/usr/bin/php. If you are not sure about the location, typewhich phpAnd view the response content.

?

Second, type the following code to ensure that/Usr/bin/phpReplace it with the actual path of the PHP executable file.

#!/usr/bin/php -qHello world

?

Save the file and make sure that the executable permission is marked. In most systems, you can usechmod +x hello-worldOr similar code to complete this operation. Then, execute the PHP file (by running./hello-worldOr, if necessary, runphp hello-world), And check whether it is running. If it runs, the installed PHP will include the command line function by default.

If the code fails to run correctly, it may become a little troublesome. There are many different possibilities for the cause. If you get a PHP-related error (except for results such as "No program found"), the problem is the input error in the code. If the PHP executable file is not found, make sure that the correct path is used. If there is no executable file named PHP, you must obtain one.

?

Obtaining PHP executable files may take different steps based on the system, but obtaining required support should not be too difficult. You can start by reading documents for a specific operating system or release.

?

Obviously, if PHP is not installed in the system, first install PHP and then try to execute the above code again. For many systems, installing PHP is all you need to do. If you want to perform more operations, sometimes you only need to use your favorite package management tool (for exampleapt-getOryum) Obtain the php cli package (the name may be slightly different) to solve this problem.

?

If the command line cannot be found in the PHP package management tool, the worst case is that you can use--enable-cliMark and re-compile PHP. In fact, the advantage of doing so is that it provides a slightly optimized system and is not a bad idea in any case. No matter which method is used, it should not be too difficult to start using it.

?

Now you have run the HelloWorld script, and the output is the result that may have been guessed. I will not elaborate on how the script works, but those who have used shell scripts and PHP should be very familiar with most of the script content. Since this first script is running without any problems (we hope so !), Therefore, we will slightly deviate from the real CLI application to see why using PHP in the command line is the best choice for all PHP programmers: debugging.

? PHP Debugging

I may only have this experience, but I often find that debugging the CLI program has evolved into a nightmare, especially when processing HTML-embedded scripts, such as Microsoft? Active Server Pages (ASP) or PHP. It is usually difficult to determine the exact meaning of a specific error message, user input may be difficult to generate again, and the whole thing will usually make you have a headache.

?

Unfortunately, although smart enough programmers can find methods that CLI can help (for example, reading input from a file or another program through one channel ), however, most problems won't be significantly mitigated by using command lines. However, CLI makes it easier to find error messages so that they can be read in the first place.

?

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

#! /Usr/bin/php-qDon <'T> code
 

?

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

?

The traditional method to solve this problem is to view the error log. For example, you may first run:

tail -f /var/log/httpd/error_log

?

Then load the page into the Linux system running Apache 2. the output is as follows:

[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 me to consider this unsatisfactory solution. On the one hand, the file log location may vary depending on the system. On the other hand, you must browse logs of irrelevant events to find the desired content, which may be a nightmare for active servers.

?

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

? Use CLI to locate and correct errors

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

php dont-code-drunk.php

?

The following output may be returned:

PHP Parse error:  parse error, unexpected T_STRING, expecting     '(' in /var/www/html/dont-code-drunk.php on line 2Content-type: text/htmlX-Powered-By: PHP/4.3.11

?

Even better! The error message is separated from other data, and you can easily view the page after making changes. In this case, it is clear that it needs'('.whileThe statement seems suitable for use here, so add a new set of parentheses to get the following source code.

#! /Usr/bin/php-qDon <'T> code
  

?

Now, run the code again to get the following output:

? Listing 1. running the result 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 many problems, but you have made some progress. You have easily extracted the required error messages, allowing you to quickly fix problems in the program and continue to handle the next issue.

?

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

? Php I/O channel

Create a simple initial goal for the first PHP script: to create a script that can read files and disrupt all rows in the file. If you want to disrupt m3u files or similar content, this feature may be convenient. This 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 be the first challenge in PHP. PHP was initially not designed to work with the user's direct keyboard input or text output. Understanding this design is crucial because any operation on the command line must be able to communicate back and forth with the user. For exampleCIn traditional programming languages suchSTDIN,STDOUTAndSTDERRComplete this operation. You can use the same channels in PHP for input, standard output, and output to error channels.

? STDOUT: echo, print, STDOUT, and php: // stdout

That is to say, PHP is designed to be used for output to the browser rather than to the CLI. it is also very simple to create an output from PHP, and it almost does not need to spend too much time thinking. Remember, anything outside the PHP tag will be directly output to the CLI, which is why the HelloWorld program above is so simple. This is why the aboveDon<'t>codeCause of the error message. It doesn't matter whether you use HTML to mark text, because the text is displayed anyway. In fact, you usually need to avoid using HTML tags because they will be printed directly to users.

?

You can also use basic functions for output. For example,echoAndprintThe command is printed to the standard output.

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

?

This will get:

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

?

Note: New lines not marked by PHP have been output,echoCommand orprintCommand. In fact, the command prompt appears again inOutput #2.Output #3.In the row. Any other printing functions of PHP will run normally like this function, and any function written back to a file will do the same.

#!/usr/bin/php -q
   

?

The above code willphp://stdoutAs the output channel, andphp://outputGenerallyphp://stdoutRun the same method. PHP of the latest version can be usedSTDOUTAs a constant rather than defining the variables used above$STDOUT.

? STDERR: STDERR and php: // stderr

STDERRAndSTDOUTVery close. All technologies used to write images to this channelSTDOUTThe only difference between those technologies is thatphp://stderrInsteadphp://stdoutOrphp://error.

? STDIN: STDIN and php: // stdin

STDINIt is the most interesting change from Web programming because it shows you real user input rather than using forms or other browser-based methods. Run the following command:

#!/usr/bin/php -q
   

?

This code should work in a similar way.cat, Returns all input to it. However, it cannot accept parameters.

? First PHP shell script

Good-from here on things will become very interesting. With the simple knowledge you have learned so far, you can create simple and useful shell scripts. In the text editor, type the following code.

? Listing 2. randomize-lines
#!/usr/bin/php -q
   

?

Now, you only need to perform a quick check to run this script:

  1. Make sure that hashbang (the first line,#!) Is set to the location of the PHP executable file described earlier.
  2. Save files
  3. UsechmodAdd executable permissions
  4. Run the program

Note: randomize-lines will fully execute the desired operation: it will disrupt the input content rows and return them in different order. This function can effectively fill the gaps in the shell script library.

?

As an application example of this script, you can use it to dynamically generate a random playlist for a music or video player. For example, to disrupt the XMMS playback list, try:

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

?

Now, raise the level.

? Command line parameters

The actual command line program uses parameters. Similarly, just like C and other similar languages, you can useargvAndargc. In particular,argvIs an array of program parameters. The first parameter is the program itself. Using this function, it is not difficult to construct a program that reads data from a file or user input based on a given parameter. For example, check the following code.

? Listing 3. randomize-lines-w-args
#!/usr/bin/php -q
   

?

Now you have such a program: a fully-running cli php program that can accept user input, list of files, and randomly arrange related content of each file.

? Conclusion

To do something better, you must first sharpen the tool. but remember: the best tool is usually not the one you want to use. Please give PHP a chance to use it in the command line interface, you will find it has become a new favorite of your shell script tool. The worst case is: it can save some Web server troubles.

?

References
  • For more information, see the original article on the developerWorks global site.
  • Read "PHP by example" and find a simple way for PHP to build complex and powerful Web-related programs.
  • PHP Freaks discusses how to use PHP on CLI.
  • Php cli has its own Web site. Who knows?
  • PHP.net is a PHP developer resource.
  • Refer to "PHP recommended books list ".
  • Browse all PHP articles and PHP tutorials on developerWorks.
  • Refer to IBM developerWorks's PHP Project Resource Center extension PHP skills.
  • To listen to interesting interviews and discussions with software developers, visit the developerWorks podcast.
  • Stay tuned to technical events and network broadcasts on developerWorks.
  • Check out recent seminars, trade exhibitions, network broadcasts, and other activities for IBM open source code developers to be held globally.
  • Visit the developerWorks open-source software technology area for a wide range of how-to information, tools, and project updates to help you develop with open source code technology and use it with IBM products.
  • Visit the Safari online bookstore to view various reference materials on open source technology.
Obtain products and technologies
  • Use IBM trial software to build your next development project, which can be downloaded or obtained from a DVD.
Discussion
  • Join 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.