Using PHP on the command line
Takeaway: Learn to use PHP on the command line with these tips and simple examples from Vincent Danen.
PHP is generally regarded as one of the most powerful and easy-to-learn Web scripting technologies, and emphasis has largely been devoted to using PHP on Web sites. However, the same power that can be harnessed to handle complex Web sites can also be used on the command line. Like Perl, PHP is a more-than-capable, dual-purpose scripting language.
There are a few minor caveats to using PHP on the command line: the first is that you need to compile the PHP CLI binary (most Linux distributions do). This will output the binary /usr/bin/php which is the CLI interpreter to PHP scripts.
Writing a PHP CLI script is as simple as:
#!/usr/bin/php<?php...?>
As you can see, about the only thing different from a Web script is the "#!" identifier, which tells the shell to run the script via the /usr/bin/php interpreter. After that, it's business as usual.
Two special variables are also available for use with command-line arguments: $argc contains the number of arguments provided to the script and $argv is an array of arguments that were passed. Command-line arguments can be easily parsed as well. See Listing A for an example.
The example is fairly simplistic, but it illustrates how easy it is to write comprehensive code for the command line. There are very few limitations to what you can script on the command line, and nearly all functions and modules that come with PHP are available for use. Certain functions, such as those dealing with cookies, are not really applicable for command-line use, but others such as database access and XML parsing certainly are.
Delivered each Tuesday, TechRepublic's free Linux NetNote provides tips, articles, and other resources to help you hone your Linux skills. Automatically sign up today!
SponsoredWhite Papers, Webcasts, and Downloads
- SprintSecure Message Protection Fact Sheet Sprint
- IBM Master Data Management: Effective Data Governance IBM
- Next Generation Mobility Now Sprint
- Advances in Data Warehouse Performance: I/O Elimination in DB2 IBM
- TechRepublic SolutionBase: Expanding storage options with Windows Storage Server TechRepublic
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET


