Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

PHP in the Command Line

By Robert Plank
2005-05-25


Arguments (not the shouting kind)

But wait, you want to use it in a crontab, which is run from the command line.  You can't just do something like:

php get.php?url=http://www.google.com

Because it'll try looking for a *file* named all that, complete with the question mark and all.  So what if you have ten different URLs to grab off ten different crontabs, but you only want one script.

How would you do all that?  It's a long brutal ordeal so prepare yourself.  Ready?

php get.php url=http://www.google.com

Yeah, that's all there is to it.  PHP's pretty cool like that, it takes the arguments after the file name and stores them in the same array you'd check anyway.

One thing you might notice is that every time you run PHP from the command line, it gives you something like this:

Content-type: text/html
X-Powered-By: PHP/4.3.3

your output here...


Those first couple of lines are the HTTP headers.  But we're not using HTTP (not loading it from a browser), so in the command line it's better to call php with the "-q" option, like this:

php -q get.php url=http://www.google.com

The "q" stands for quiet, and will refrain from giving you the HTTP headers.  If you're just piping the script to /dev/null (to nothing) in a crontab, it doesn't really make a difference but you should try to make this a habit when running PHP from the command line.

That's enough for you to at least get started.  If you still feel liking poking about with the things PHP can do in the command line, you can try prompting a user for keyboard input, like this:

<?php

echo "Give me your name: ";
$data = fopen("php://stdin", "rb");

while (
1==1) {
   
$chunk = fread($data, 1);
   if (
$chunk == "\n" || $chunk == "\r") break;
   
$input .= $chunk;
}
fclose($data);

echo
"Hello $input!\n";

?>


Remember, that only works when PHP is run from the shell.

If you have PHP installed in Windows on a local machine of yours, you can also see what happens when you try to read (and write) to filehandles like "COM1:" and "LPT1:" ... yep, you guessed it, the serial port and printer port.  If PHP isn't installed on the computer you're using now then don't bother.  But it is possible to use PHP to print and interact with your peripherals as well.

You're welcome.

Tutorial Pages:
» Listen closely and you'll hear the ocean
» Pipe down over there
» Here today, gone tomorrow
» Put it together
» Arguments (not the shouting kind)


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1

Ask A Question
characters left.