November 21, 2008

Running PHP Scripts from a Command Line

Another great aspect about PHP is that you don't even need Apache to run your scripts. If you don't need any special GUI or your script takes so long that your page is timing out before it can finish, try running it from the Command Line.

Preparation:
  • Install PHP - Of course you have to install PHP! I felt silly adding this to the list, but I felt I had to.
  • Add the PHP installation directory as a Value in the Environment Variables - To do this, Right click My Computer->Properties->Advanced->Environment Variables. Look at the bottom in the System Variables for the Variable name, Path. Select Path and click Edit. Check to make sure that your install directory is included in the Variable Value path. For example, I should see in my path, C:\PHP. If the is not, add it to the beginning of the Path and separate it with a semi-colon (C:\PHP;). This is necessary so you can just type PHP MyScript.php while you are in the appropriate script directory.


Using the Command Line

This sections is for the complete newbie to the command line.

  • To open the Command Prompt, go START->RUN->type cmd
  • From here, you will need to navigate to where your PHP script you want to run. To change directories, use the cd command. For instance, if I was running a script out of the Default Apache DocumentRoot, I would type the following: cd C:\Apache\Apache2\htdocs [enter]. At this point, you are in the same directory as the script you want to run. Now type: php MyScript.php


  • With this in mind, you could actually call your PHP script much in the same way. After you enter into the Command Prompt at the very beginning type: php C:\Apache\Apache2.2\htdocs\MyScript.php [enter]


  • If your script contains HTML or any other non-PHP elements, they will just be printed to the screen
Conclusion

The reason you added C:\PHP to the environment path is so you didn't have to navigate to the PHP installation directory to access PHP.exe. Using this strategy, you can now build batch file programs that will run your scripts for you. For instance, I wrote a script that will update thousands of records in a MySQL database. The process takes over 10 minutes and I need to run it every day. All I did was created a text file called Update_Data.bat and add one line of text to the file: php C:\Apache\Apache2.2\htdocs\MyUpdate.php Now all I have to do is click Update_Data.bat and walk away without worries of a page time out.

No comments:

Post a Comment