Now that you have installed all the support software for running PHP, you are ready to learn how to do a PHP script. Writing a PHP script is very simple. No special software is needed, except a text editor like Notepad in which the script is written.
We should begin with some general PHP syntax rules. First, all single-line statements must conclude with a semicolon. If PHP doesn’t find a semicolon at the end of your statement, then it will continue parsing the file until it finds one, ignoring any white-spaces or empty lines. In addition, statements that exceed a single line (such as most conditionals) must be surrounded by { and } characters. Finally, the double forward slash (//) represents a comment and everything past those characters until the end of the line will be ignored by PHP.
A PHP file normally contains HTML tags and some PHP scripting code. A PHP scripting block always starts with
<?php and ends with ?>. A PHP scripting block can be placed anywhere in the document.There is a PHP script in the example given below. This script will display the words “Hello World!” in the web browser. There are two basic statements to output text on the browser with PHP: echo and print. In the example given below, the echo statement is used to display text.
|
Always remember to save PHP’s files with the extension “.php” – this is very important, because it tells the server how to treat these files, and run the appropriate interpreter to “understand” their contents. So just go ahead and give it an easy-to-remember name like “first.php”. If you run the web-server on your own computer, copy the file to the root location of your web-server (usually c:\inetpub\wwwroot\). If you’re not running the server on your computer, then you must upload the file to your server. After you’ve put your script where it should belong, you must open it via your web-browse. So point your web-browser to the path of the script according to your server’s address – for example, if you’re running a server on your own computer, then just load into your web-browser the file http://localhost/first.php
If everything goes ok, then you will see “Hello World!” in your web-browser’s output window. If PHP is not installed or the server didn’t recognize the file’s extension, you will see the source code of the script.
While the first script is pure PHP, you can incorporate it into a HTML document. Copy the code below, save it as “second.php” and load it into your web browser.
|
The output of this last script will be pretty much the same as the first one, except that the new document will also have a title: “First PHP Script”, and the welcome message will be written using bold characters.
Note: If you view the source html code from the browser application, all php code is hidden. It was all processed before the browser application could view the page.