Your First PHP Code
The following is a short extract from our new book, PHP & MySQL: Novice to Ninja, 6th Edition, written by Tom Butler and Kevin Yank. It's the ultimate beginner's guide to PHP. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.
Once the web server has executed the PHP code embedded in a web page, the result takes the place of the PHP code in the page. All the browser sees is standard html code when it receives the page, hence the name “server-side language.” Let’s look at simple example of some PHP that generates a random number between 1 and 10 and then displays it on the screen:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Random Number</title> </head> <body> <p>Generating a random number between 1 and 10: <?php
echo rand(1, 10);
?> </p> </body> </html>
Most of this is plain html. Only the line between
?> is PHP code.
<?php marks the start of an embedded PHP script and
?> marks its end. The web server is asked to interpret everything between these two delimiters and convert it to regular html code before it sends the web page to the requesting browser. If you right-click inside your browser and choose View Source (the text may be different depending on the browser you’re using) you can see that the browser is presented with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Random Number</title> </head> <body> <p>Generating a random number between 1 and 10: 5 </p> </body> </html>
Notice that all signs of the PHP code have disappeared. In its place the output of the script has appeared, and it looks just like standard html. This example demonstrates several advantages of server-side scripting …
- No browser compatibility issues. PHP scripts are interpreted by the web server alone, so there’s no need to worry about whether the language features you’re using are supported by the visitor’s browser.
Truncated by Planet PHP, read more at the original (another 652 bytes)