New Users: Quick PHP CLI

From The Uniform Server Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

MPG UniCenter

New Users: Home | Quick PHP CGI | Quick PHP CLI | Quick PHP Info

Quick PHP CLI 3.5-Apollo

On the previous page I covered PHP effectively running in CGI (common gateway interface) mode to serve web pages. I mentioned the modules dual nature this page looks at its scripting capabilities (CLI). Combine this with batch files and like Perl provides unlimited power to manipulate files and system resources.

Interestingly Perl and PHP core component consists of two files; these are portable hence you can use them independently of Uniform Server. This portability you can use to great advantage, for the examples on this page I decided it was best to move the PHP engine to a working folder however if you wish you can use the existing Uniform Server’s location the choice is yours.

PHP Engine -Working folder

All we need to do is make a copy of the two files and place them in a working folder. You can use any drive and name the folder whatever you like. I tend to name my folders with a suffix a_ the only reason for doing this when viewed in Explorer brings them to the top of a folder tree.

One tip keep your file and folder names short this saves you a lot of typing when using a command window.

To create a working copy of PHP follow these instructions :

  1. On C drive create a new folder named a_php
  2. Navigate to the folder *\Uniform Server\udrive\usr\local\php
  • The two files you are looking for are:
    php5ts.dll (engine)
    php.exe (interface)
  1. Copy the above two files to folder c:\a_php

Interface file php.exe is the “PHP Command Line Interpreter” it receives commands both from you (command prompt CLI) or another program, decides on the appropriate action and returns information.

A PHP script is passed to the main engine php5ts.dll “PHP Interpreter” this compiles a script and returns the result via the interface back to you or the calling program.

Top

Test Script

This test script is as old as the hills, run Notepad (or any other text editor) and type the following line into it:

<?php
print "Hello World";
?>

Save the file to folder c:\a_php and name it test.php


Note 1: All PHP scripts you write need to have a file extension of .php (The php extension is not mandatory you can use whatever you like however because of file associations its best to keep to php.)

Before you can run the script you need to open a command prompt as follows:

Top

How to run a command prompt

The following shows how to start a command prompt however unless you like typing I do not expect you to sit there using it full time. I have shown it to highlight the commands you need to type in.

These commands are important, they are used in batch files to make life easier I cover this later. Aldo shown is the method of running a PHP script.

  1. Start a command prompt Click Start > Click Run > Type in cmd click OK
    This opens a small black window referred to as the command prompt.
  2. Type the following commands into this window:
  • Type in cd .. press enter key – this takes you up one level in the folder tree
  • Type in cd .. press enter key – again takes you up one level
  • Display: C:\> - This is your top level on C drive if you type cd .. again you will go no further you are already at the top
  1. Type cd a_php press enter - this changes the folder as indicated by the prompt c:\a_php>
  2. Type dir press enter - this displays the folder content (the two files you copied to it)
  3. Type php.exe -v and press return -- PHP information will be displayed.
  4. Type php.exe test.php press enter key
  5. Type pause press enter key -- this command results in "Press any key to continue . . ."
  6. Type exit press return -- this ends the command prompt

Those eight steps result in a display similar to this:

Steps 2 and 3: Are really demonstrating how to move up and down the folder tree. The two full stops move you up one level, while cd stands for change directory (folder) effectively moving you down the folder tree.

Step 5: Is of importance it shows how to pass a switch to PHP in this case display its version information. If you run the same line with –h switch it displays a whole host of switches you can use.

These two I find most useful:

  • -n No php.ini file will be used
  • -l Syntax check only (lint)

Switches are predominately used when running PHP as CLI here is the full list:

C:\a_php>php -h
Usage: php [options] [-f] <file> [--] [args...]
php [options] -r <code> [--] [args...]
php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
php [options] -- [args...]
php [options] -a

-a Run interactively
-c <path>|<file> Look for php.ini file in this directory
-n No php.ini file will be used
-d foo[=bar] Define INI entry foo with value 'bar'
-e Generate extended information for debugger/profiler
-f <file> Parse and execute <file>.
-h This help
-i PHP information
-l Syntax check only (lint)
-m Show compiled in modules
-r <code> Run PHP <code> without using script tags <?..?>
-B <begin_code> Run PHP <begin_code> before processing input lines
-R <code> Run PHP <code> for every input line
-F <file> Parse and execute <file> for every input line
-E <end_code> Run PHP <end_code> after processing all input lines
-H Hide any passed arguments from external tools.
-s Display colour syntax highlighted source.
-v Version number
-w Display source with stripped comments and whitespace.
-z <file> Load Zend extension <file>.

args... Arguments passed to script. Use -- args when first argument
starts with - or script is read from stdin

--ini Show configuration file names

--rf <name> Show information about function <name>.
--rc <name> Show information about class <name>.
--re <name> Show information about extension <name>.

Step 6: Shows how to run your PHP script. Main point here you must specify the executable (php.exe) you cannot just type in test.php and expect it to run. We are running PHP in a portable environment; by this I mean Windows has no idea what to do with the file you typed in, since there is no Windows path to the executable and no file extension .php association with any executable. If running a script from another folder not containing the executable (php.exe) the full path to it must supplied. For example c:\a_php\php.exe some_script.phpl

Step 7: I slipped this in to show you what a pause command displays; it stops execution and waits for a response from a user, absolutely not required when running interactively with a command window. You will see the importance of this command shortly.

Step 8: Exit kills off the command prompt.

I very rarely use a command prompt; my preference is to run a batch file containing the above commands. All I need to do is double click on that batch file and let Windows do the donkeywork.

Top

Batch file processing

Using a text editor create a new text file and type this line into it:

php.exe -n test.php

Save it to folder c:\a_php with the following name run.bat Run this batch file from Explorer by double clicking on it.

I hope you were impressed by the result, batch file ran, followed by PHP running your script and finally batch file ending. I admit a little fast you probably only saw the command window for a short time. Now add the pause command to your batch file and run it again.

php.exe -n test.php pause

Now you understand the importance of the pause command it gives you a sporting chance to see your PHP script in action. The switch -n informs PHP we are not using a configuration file.

Check Bat

That single batch file will allow you to run any of your scripts however before you get carried always make sure your scripts compile first before running them. For this I use a second batch named check.bat and add switches to the php.exe the two I highlighted above. Create a new text file and add the following lines:

php.exe -n -l test.php
pause

When run, this batch file performs a syntax check (-l) it does not execute the PHP script.

Before running the above batch file, create an error in the test file.
For example edit test.php copy and paste the print line several times, on any line remove a quote save the file. Now run check.bat

Result:

C:\a_php>php.exe -n -l test.php

Parse error: syntax error, unexpected T_PRINT in test.php on line 7
Errors parsing test.php

C:\a_php>pause
Press any key to continue . . .

Correct the error and run it again. With all the errors removed you can use run.bat to see what your script produces.

Top

Summary

Using only two very basic batch files you can run PHP independent of UniServer and Windows it makes an excellent portable development tool for PHP programs.

  File name: run.bat  
php.exe -n test.php

pause

 

  File name: check.bat  
php.exe -n -l test.php

pause

Top

Relative paths

I mentioned you must use full paths to the php.exe file that’s not strictly true! You can use relative paths, so long as they lead Windows to the executable.

Create a new folder in c:/a_php named down now move the two bat files (run and check) into it.

When you run these batch files Windows will be unable to find either the php.exe or your test.php script and produce errors similar to this:

  File name: run.bat  
C:\a_php\down>php.exe -n test.php

'php.exe' is not recognized as an internal or external command,
operable program or batch file.

C:\a_php\down>pause
Press any key to continue . . .

 

  File name: check.bat  
C:\a_php\down>php.exe -n -l test.php

'php.exe' is not recognized as an internal or external command,
operable program or batch file.

C:\a_php\down>pause
Press any key to continue . . .

To the rescue the two dots and a back slash, these move up the folder tree one level. Add these to the paths in your two batch files they will look like this:

  File name: run.bat  
..\php.exe -n ..\test.php

pause

 

  File name: check.bat  
..\php.exe -n -l ..\test.php

pause

One extremely important point PHP uses as a reference point the location (path) of the program that called it. It does not use the path that it resides in.

When PHP uses relative paths in calculations these are referenced to the location of the calling program (cwd current working directory) in our case the batch files.

Top

Complete example

Expanding the above introduction I am now going provide a more practical example this uses some of the system commands and introduces user input and output.

Set-up

Create a folder anywhere you like choose a suitable name I will be using php_examples.

Copy the two files php.exe and php5ts.dll located in Uniform Server’s folder *\Uniform Server\udrive\usr\local\php.

Create four blank text files named test.php, go.bat, check.bat and run.bat add the text shown below to each file:

File Name Text Comment
test.php   Your test script, you can choose any name you like, must have the extension .php if you change the name change batch files to match.
check.bat php.exe -n -l test.php
pause
Run this first to check your script (test.php) for syntax errors. It does not run your script only checks for errors. To give you a chance to view any results pause is included to halt execution of the bat file until a key is pressed.
run.bat php.exe -n test.php
pause
This runs your script (test.php) again pause is included to give you a chance to view any output from your script.
go.bat php.exe -n test.php Runs your PHP script (test.php) and closes. Assumes you are not outputting text to the command prompt. If you do include a pause command in your script or use run.bat.

Note: The above file names are insignificant you can use whatever you like however do not change the file extension.

Hello World Script

Add the following lines to test.php

<?php
print "Hello World\n";
print "Hello World\n";
print "Hello World\n";
?>

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\a_php\php_examples>php.exe -n -l test.php

No syntax errors detected in test.php

C:\a_php\php_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat C:\a_php\php_examples>php.exe -n test.php

Hello World
Hello World
Hello World

C:\a_php\php_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

PHP script is run and displays the out from the print commands

Waits for user input

go.bat Screen flashes No pause in the script.

Top

Streams

Data is pushed around a PC and across the Internet in a serial format consisting of a stream of ones and zeros. Data from a keyboard and data to a screen are referred to as the standard input and standard output streams. The source and destining of these streams can be changed, what is interesting, data can be treated as file input and output. These streams are automatically available to PHP CLI and identified with the constants STDIN and STDOUT respectively.

The reason I mention this, you can use STDIN with fgets(), fread(), fscanf() and fgetc() to produce powerful input scripts. In addition using STDIO and STDERR with fwrite()you can separate output to the user while hiding any error messages useful for debugging.

User Input

Open test.php delete its content and add the following lines:

<?php
 fwrite(STDOUT, "Enter some text:\n");      // Prompt user  
 $name = fgets(STDIN);                      // Read the input
 fwrite(STDOUT, "Text entered was: $name"); // Output to user
 exit(0);                                   // Exit no errors
?>

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\a_php\php_examples>php.exe -n -l test.php

No syntax errors detected in test.php

C:\a_php\php_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat C:\a_php\php_examples>php.exe -n test.php

?Enter some text:
fred123
Text entered was: fred123

C:\a_php\php_examples>pause
Press any key to continue . . .

Prompt user: fwrite(STDOUT, "Enter some text:\n");

Get user input: $name = fgets(STDIN);
Write result: fwrite(STDOUT, "Text entered was: $name")

Pause from: Batch file

go.bat Screen flashes As above

Note: Script exits and batch file closes hence you will not see a result.

Top

Reading a text file

Create a new text file named data.txt and add the following lines

First Line
Second Line
Third Line

Open test.php delete its content and add the following lines:

<?php

$filename ="data.txt";
$filearray = @file($filename);

if($filearray){
 while (list($var, $val) = each($filearray)){
  ++$var;
  $val = trim($val);
  print "Line$var: $val \n";
 }

 foreach ( $filearray as $line => $item ) {
   $item = trim($item);
   print ("$line : $item\n");
 }
}

else{
 print ("Could not open $filename");
}

exit(0);
?>

What the lines do:

Line Comment
<?php  
$filename ="data.txt"; Creates a variable and sets it to the file name we are using.
$filearray = @file($filename); Creates a variable that is automatically converted to an array when the file is read line by line into it using file(). The @ suppresses any error messages, since we are using the else for this.
if($filearray){ Check to see if file array contains data.
 while (list($var, $val) = each($filearray)){

  ++$var;
  $val = trim($val);
   print "Line$var: $val \n";
 }

This uses a while loop and each() function to iterate through the array line by line until there is no more data to read. Increment $var each time through the loop, this is used to display a line number. Trim is used to remove the new-line just to show you how it is done. it is inserted again in the print statement.
 foreach ( $filearray as $line => $item ) {

  $item = trim($item);
  print ("$line : $item\n");
 }
}

This shows an alternative method of iterating through the array. The point of this is to shown that you can manipulate a line of text before either printing, saving back to the array or outputting to a file.
else{

  print ("Could not open $filename");
}

If the array is empty the file could now be open or there was no data hence display some message.
exit(0);

?>

Exit it with no errors

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\a_php\php_examples>php.exe -n -l test.php

No syntax errors detected in test.php

C:\a_php\php_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat C:\a_php\php_examples>php.exe -n test.php

Line1: First Line
Line2: Second Line
Line3: Third Line
0 : First Line
1 : Second Line
2 : Third Line

C:\a_php\php_examples>pause
Press any key to continue .

The file is read into the array.

The two section are displayed.

The batch file generates a pause and waits for user.

go.bat Screen flashes As above

Note: Script exits and batch file closes hence you will not see a result.

Top

Write to a text file

Open test.php delete its content and add the following lines:

<?php

$file ="new_data.txt";

$some_data[]="New line one";
$some_data[]="New line two";
$some_data[]="New line three";

$mystring = implode("\n",$some_data);

$numbytes = file_put_contents($file,$mystring);
print "Number of bytes written = $numbytes";

exit(0);
?>

What the lines do:

Line Comment
<?php  
$file ="new_data.txt"; Creates a variable and sets it to the file name we are going to create or overwrite.
$some_data[]="New line one";

$some_data[]="New line two";
$some_data[]="New line three";

Create an array with some data in it. Note the text does not contain a new-line.
$mystring = implode("\n",$some_data); The implode() function converts an array into a string by inserting a separator (I am using new-line) between each element.
$numbytes = file_put_contents($file,$mystring); file_put_contents() function writes mystring to the named file. If the file does not exist creates it, otherwise it overwrite the file contents.
print "Number of bytes written = $numbytes"; file_put_contents() returns the number of bytes written to the file we print this out.
exit(0);

?>

Exit it with no errors

From explorer run the batch files (double clicking on file name). Results as follows:

File Name Result Comment
check.bat C:\a_php\php_examples>php.exe -n -l test.php

No syntax errors detected in test.php

C:\a_php\php_examples>pause
Press any key to continue . . .

Batch file passes commands to the command prompt hence the display.

Passes the syntax check

Waits for user input

run.bat C:\a_php\php_examples>php.exe -n test.php

Number of bytes written = 40
C:\a_php\php_examples>pause
Press any key to continue . . .

The string is written to the file.

The number of bytes is displayed.

The batch file generates a pause and waits for user.

go.bat Screen flashes As above

Note: Script exits and batch file closes hence you will not see a result. Other than the file created.

new_data.txt New line one

New line two
New line three

Lines written to file.

Top

Summary

I have shown how easy it is to use PHP CLI. You can avoid a command prompt and all its associated typing by using three batch files. Uniform Server’s prime use of PHP is in CGI (Dual mode of the CLI module) mode to serve interactive pages.

Top


Ric