Core PHP

Lesson 1: Creating Web Pages in PHP

The purpose of this lesson is to explain how a web server processes PHP to create a web page when one is requested. Before learning PHP, you should have a solid grasp of HTML and CSS; you should watch our HTML and CSS courses if you need to to learn them. Also, you should have XAMPP installed and know how to set up a web server as I did in PHP lesson 0.

The PHP Language

PHP is strictly a server-side language. That is, it runs on the server and not in the browser. So, when a page is requested from a server, the server runs its PHP code to generate the HTML document that is sent to the browser to be displayed. To see this, consider this program from lesson 0:

<?php

$sHTML = <<<HTML_PAGE
<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
    <h1>Welcome to XoaX.net!</h1>
  </body>
</html>
HTML_PAGE;

echo $sHTML;

?>

The delimiters <?php and ?> designate the beginning and ending of a portion of the code. So, everything between these delimiters is PHP code. In the program, the variable $sHTML is assigned the value of the string that is between the two lines with HTML_PAGE on them. You should recognize this as an HTML document. The next echo statement prints the value of variable $sHTML, which is just the HTML document. So, the whole effect of this program is to output this HTML document:

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
    <h1>Welcome to XoaX.net!</h1>
  </body>
</html>

If you run this program by typing localhost into the browser, as I did in lesson 0 and right-click the page and select "View page source" you will see just this HTML document. This demonstrates that only this HTML was returned from the web server. In fact, if you change the "index.php" file to have only the HTML document, it will generate the exact same output. So, the PHP is not really necessary, in this case, but it will be when we want to do more complex things.

A Simple PHP Program

To demonstrate how a PHP program can do something that HTML can not do, consider this program that simulates a coin flip:

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
<?php
    $sCoinFlip = (mt_rand(0,1) == 0 ? "Heads" : "Tails" );
    echo "<h1>".$sCoinFlip."</h1>";
?>
  </body>
</html>

If we save this code as our "index.php" file and un it by typing localhost into a web browser, we can repeated run it by hitting the refresh button. It will generate "Heads" half of time and "Tails" half of the time. This program simple demonstrates of some of the power of PHP and how to insert PHP into an HTML document.

 

© 2007–2024 XoaX.net LLC. All rights reserved.