Home >Backend Development >PHP Tutorial >In-depth analysis of PHP CLI script code examples_PHP tutorial
Our first method for
is to use php -f /path/to/yourfile.php. Call the PHP CLI interpreter and pass parameters to the script. This method first requires setting the path of the php interpreter. Before running the CLI on the Windows platform, a command similar to path c:php needs to be set. This also loses the meaning of the first line of the CLI script, so this method is not recommended.
The second method is to first run chmod+x
Let’s take a look at how to write PHP CLI scripts.
Write a CLI script
First create a PHP script named myfile.php for running the PHP CLI script. The script is simple and just displays "Hello PHP CLI!" The script code is as follows:
<ol class="dp-xml"> <li class="alt"><span><span>#!/usr/local/bin/php –q </span></span></li> <li> <span class="tag"><</span><span> ?php </span></li><li class="alt"><span>//Windows平台上,上行应该为:<br />#!C:phpphp.exe -q </span></li><li><span>echo "你好 PHP CLI!"; </span></li><li class="alt"><span class="tag">?></span><span> </span> </li> </ol>
Don’t forget to set the executable permissions for the file:
$ chmod 755 myfile.php
Then enter the following command directly , press Enter to run:
$ ./myfile.php
If you want to run the script under Windows system, you do not need to set the file attributes, you can run the PHP CLI script directly .
Once again: If you are on the Windows platform, the first line of the CLI script must write the correct location of php.exe, like this (In addition, if you want to add a comment statement to the CLI script, you must The comment is written in the PHP tag, because the CLI interpretation only recognizes the first line, and it is considered a syntax error if it is not in the PHP tag):
#!C:phpphp.exe -q
In this way, you can Seeing that the information has been printed on the command line proves that the PHP CLI script has been successfully run.