Combining PHP with HTML to power websites

PHP is a powerful language on its own, but in combination with HTML it powers the majority of today's websites.

Now it’s time to get down to the real task at hand - actually creating a working web-page using PHP. In this tutorial, I’ll show you how to create a simple web-page to demonstrate how to add a little bit of dynamic jazz to an otherwise static site.

I’m assuming, for this tutorial, and throughout the rest of the tutorials, that you have at least a basic knowledge of HTML - enough to be able to use simple tags such as <br>, <a>, <form> and so on. If not, why not check out any of the decent HTML tutorials around the web - Google for “HTML Tutorial”

HTML + PHP = HTML

In the previous tutorial, we saw how a PHP file could be created by using the start and end tags, <?php and ?>. We also saw how these tags could start and stop as often as you wished. Within the context of a standard PHP file, this doesn’t make much sense. After all, what’s the point of stopping and starting the PHP code if we’re just going to be executing more of the same PHP?

Take the following, as an example

<?php echo "The solution to 2 + 2 is "; ?>
<?php echo 2 + 2; ?>

There’s really no reason to include two sets of opening and closing tags. You could easily just write

<?php echo "The solution to 2 + 2 is ";
echo 2 + 2; ?>

But - when considering how PHP can be used to generate HTML files, the answer to our query, “why open and close tags so often?” lies in the fact that, between those PHP tags, we can output HTML content. Take the following code snippet as an example. This is the full text from a PHP file

<?php echo "A "; ?>
sample PHP file
<?php
 echo "And here is the second line";
?>

Run this, and we see the output

A sample PHP file
And here is the second line

Now, what’s going on here? You might well have guessed by now, the “echo” command is used to output data to the screen. But there’s no echo command on the second line, so how is this text appearing? And more importantly, you might ask, where’s the semicolon? I did say in an earlier tutorial that any PHP code without a semicolon at the end of each statement will fail. But the important thing to note here is that on line 2, that’s not PHP code.

Remember from the previous tutorial that anything contained between <?php and ?> tags will be interpreted as PHP? Likewise, anything not contained between those tags will not be interpreted as PHP, and will be output directly to the screen without any modification.

PHP files can contain both static text and executable PHP code. Whether or not a specific part of the file is rendered directly as text, or intepreted as PHP code is down to the use of the opening and closing PHP tags. Whenever the code is between the <?php and ?> tags, it will be executed as PHP code.

When creating a PHP file for use as a webpage, a good way to think about it is that you’re really just creating an HTML file but with sections of PHP code inserted into the HTML. This way, you can focus on dealing with the layout and design aspects of the site when you wish to just work with HTML and when necessary, you can insert a little bit of PHP to display e.g. the current date and time, or to work with some other variables.

Executing PHP code within static text

So, again, to summarise:

  • In any section of the file between <?php and ?> tags, the code is treated as PHP code - any statements such as “echo” are executed, and any errors, such as missed semi-colons, cause the execution of the file to fail, and halt output at that point

  • In any section of the code not between <?php and ?> tags, the code is treated as plain text, and it is printed directly to screen as-is, with absolutely no modification

For example

echo "A sample PHP file";
<?php
  echo "And here is the second line";
?>

What do you think happens here? That’s right…

echo "A sample PHP file";
And here is the second line

The first line of “code” is not executed, simply because it is not treated as PHP code, but instead as pure HTML - quote marks, “echo” and all.

So, when you are creating your PHP file, you can write it as if you were just creating a plain HTML file. Whenever you are ready to add in any executable PHP code, simply insert the tags <?php and ?> and anything between those tags will be treated as PHP and executed as such.

Here is an example of a (perfectly valid) PHP file, containing all the HTML markup needed to display an HTML page

<?php
  $your_name = "Bob";
?>
<html>
  <head>
    <title>My First PHP Application! By <?php echo $your_name; ?></title>
  </head>
<body>
  <h2>This page will tell you the current date and time</h2>
  <p>The current date/time is <?php echo date("F j, Y, g:i a");  ?></p>
</body>
</html>

Notice how we can execute PHP code anywhere within the document, even before the HTML content begins. This is the key to building webpages with PHP, by using PHP to output certain sections of text, and using HTML to build the website content, you can create powerful templates which utilise the power of PHP to display ever-changing content.

Generating HTML tags with PHP

As we’ve already seen, with the newline (<br/>) tags, you can even output HTML tags with PHP. Take the following code

<p>
<?php
  echo "This is a line of <b>HTML</b>!";
?>
</p>

This will output the following HTML code

<p>This is a line of <b>HTML</b>!</p>

And you can see how, from this, you can produce many more complicated examples to dynamically build up the HTML content of a page using PHP

New lines in HTML and PHP

You might have noticed in my earlier example, I used the <br> HTML tag to split the output over two lines. This is a common enough occurance in HTML, but when using PHP, a little extra thought has to be taken. Take the following code snippet, for example

<?php
  echo "This is on line 1";
  echo "And this is on line 2";
?>

This will produce, as seen on the browser screen..

This is on line 1And this is on line 2

Most certainly not on different lines! The way to get around this is to print out the <br> HTML element along with the text in PHP, i.e.

<?php
  echo "This is on line 1<br/>\n";
  echo "And this is on line 2";
?>

This will produce, as seen on the browser screen..

This is on line 1
And this is on line 2

Voila! Excellent. But, there’s another thing to consider. When you create a web page and send it to your browser using PHP, PHP is generating the HTML code and text for you, and if you do this in the same way as in the previous example, you’ll end up with the following HTML code passed to the browser

This is on line 1<br/>And this is on line 2

No bad thing, of course - after all, the visitor to the web page never sees the HTML code, and instead sees the result on the browser as you want it to be formatted, with the <br/> tag rendered as a new line. But what if you want your HTML code nicely laid out too?

If you have a large number of PHP echo commands one after the other, then you’ll end up with a lot of HTML code all on the same line. Still, all very well, since it will be printed to the browser screen in a readable format, and split into new lines at the edge of the screen. But it’s a pain to debug! And it doesn’t look terribly professional to any nosey web developer who wants to sneak a look at your source code.

To get around this, use the character \n in your text - this is what is known as an “escaped character”, and it will not show up in the output, but will affect the formatting - in this case, adding a new line into the HTML code itself. Other notable escape characters include \t for a tab space, and \r for carriage return (\r is sometimes required in combination with \n to produce a new line on certain systems)

e.g.

<?php
  echo "This is on line 1<br/>\n";
  echo "And this is on line 2";
?>

Giving us, in the source code of the HTML file

This is on line 1<br/>
And this is on line 2

Using the URL to insert data

One very useful function of PHP is the way in which it can dynamically adjust the content of a specific webpage based on parameters passed into it through the URL

How many times have you seen URL addresses like..

http://www.mywebsite.com/page.php?page=1&section=articles
http://www.randomsite.com/index.php?article=656
http://www.aphpwebsite.com/file.php?code=y&value=41.55

These are examples of URLS with query strings attached to the end. The query strings in this case are “page=1&section=articles”, “article=656″, “code=y&value=41.55″. E.g. everything after the question mark

What is the query string?

Put simply, the query string is a way to pass variables from the browser’s address bar into the site itself. Let’s say we have a website where we want to be able to place a specific person’s name into the code. We could do this by adding the name of the person as a variable into the PHP code itself

$name = "Jim";
echo "Hello $name, how are you?";

Hello Jim, how are you?

But, that’s not much use if we want to be able to easily change the name we’re using here. Now, let’s take a look at a useful query string we might be able to use in this case

http://www.mywebsite.com/file.php?name=Jim

Here, we’ve appended the query string “name=Jim” onto our URL. This is the same URL we’d normally access to view the file “file.php”, but now we’re just adding on some more data. It doesn’t affect how the PHP file loads, but now we have access to a new variable within the PHP file

The $_GET array

In a later section, we’re going to look closer at how arrays work, but for now, I’m going to introduce to you a built-in PHP array called $_GET.

Whenever you run a PHP script, you will always have access to an array called $_GET. This value contains within itself all the variables that are present in the query string and we can access these variables using a particular notation.

echo "Hello {$_GET["name"]}, how are you?";

If we’re using the URL as we wrote it previously, we’ll get from this

Hello Jim, how are you?

Clever eh? What’s happening here is that PHP is taking from the query string, the value of “name” and storing it within the $_GET array. Array notation will be explained in a later tutorial, but for now, all you need to know is that you can access values within an array by using the above notation.

Similarly, if we were to use the URL

http://www.mywebsite.com/file.php?name=123Bob

We’d get

Hello 123Bob, how are you?

So you see how using the query string to pass in data can be extremely useful.

Be aware though, that in certain situations, passing data directly from user input into your PHP application can be A Very Bad Thing. Imagine a situation where e.g. you’re querying a database based on a specific name entered by a user, so e.g. http://www.website.com?name=jim is designed to print all users with the name ‘Jim’. Unless a great deal of care and far more advanced techniques than this tutorial covers are implemented, this gives an avenue for a malicious user to do a lot of damage to your site

Don’t be overly concerned about that for now though, just look at the $_GET examples above as an outline of the very powerful connection which exists between the web browser and PHP, allowing for a great deal of dynamic functionality.

Multiple query string variables

It’s possible to pass in multiple variables using the query string too. All we need to do is make sure we seperate the variables using the ampersand symbol (&), like so

http://www.mywebsite.com/file.php?name=Jim&age=25

Here, PHP will add the values of “name” and “age” into the $_GET array, to be accessed as follows

echo "Hello {$_GET["name"]}, how are you? You are {$_GET["age"]} years old";

Giving us

Hello Jim, how are you? You are 25 years old

Similarly, we can adjust these variables again…

http://www.mywebsite.com/file.php?name=Alan&age=5001

Giving us

Hello Alan, how are you? You are 5001 years old

Further uses for $_GET to create multiple pages

A particularly useful application of the $_GET array is to specify multiple pages to be used in a site template, so that we can create multiple website pages without needing to worry about recreating the template code for each one. Take the following HTML code as an example

<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <h2>This is my website</h2>
    <p>This is some content on my website</p>
  </body>
</html>

Now, what if we wanted to have another page, but just changing the content between the “body” tags? We could create a seperate file with the same HTML markup, but an easier way is just to use PHP to dynamically build our site by passing in variables through the $_GET array.

Let’s say we wanted two pages, “main page” and “about us”. Using PHP, we can seperate out the content of these files into seperate text files.

In this example, we could create two seperate text files, like so

//in the file aboutus.php.inc
<h2>About Us</h2>
<p>Here's a little bit of text about us</p>

//in the file mainpage.php.inc
<h2>Main Page</h2>
<p>This is the main page</p>

These files will be saved in the same directory as the main PHP file, which would look a little something like this

<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <?php
    if(file_exists($_GET['section'].".php.inc")){
      include($_GET['section'].".php.inc");
    } else {
      echo "That section couldn't be found";
    }
    ?> 
  </body>
</html>

Let’s take a look at what’s going on here. Some of the code used in this file may look a little complex if you don’t know about the use of functions or strings. If you wish to read up on these topics first, you can skip ahead to the “variables” tutorial to get an overview of strings. For now though, I’ll give a brief overview of what this code achieves.

Here, we’re using a value stored inside $_GET called “section” [Line 7]. We’ll see in just a moment how to use this, but for now, all that’s important to know is that here we’re using a function called file_exists() to check that a specific file exists (and it’s no surprise that the function does exactly what its name suggests!). In this case, we’re using the value of $_GET['section'] - let’s say in this case that it is “mainpage”. Here we check that “mainpage.inc.php” exists. In our case, it does, so we use a second function include() [Line 8], which reads in the text from the file we saved earlier, mainpage.inc.php and uses that text to construct the page

We can see how this might work with our two required pages, “about us” and the “main page” by using the following URLs to access our file

http://www.mywebsite.com/index.php?section=aboutus
http://www.mywebsite.com/index.php?section=mainpage

These two URLs will cause the PHP script to look for the files aboutus.inc.php and mainpage.inc.php and read in their contents.

Headers and Whitespace

When dealing with PHP, there are certain situations in which it is vitally important that the PHP output comes before any static HTML text. Usually, when working with sessions and headers, care has to be taken that you don’t place even one blank space before the PHP code.

Headers are the information that is sent before any HTML output on a web-page, and if any content does appear before the headers are processed, then the server will simply ignore them. This is a common cause of errors when working with sessions, as a rogue whitespace or character slipping in can prevent the server from recognising a logged-in user and provoke several hours of infuriating code debugging!

  <?php
  headers(...);
  //this won't work - see the couple of spaces before the "<?php" tag?
?>

<?php
  headers(...);
  //this is better, there is no "white-space" before headers()
  //even though there are spaces _within_ the <?php tags
?>

So be careful that you haven’t let any characters slip in before sending the headers, even in external files you have added with include() or require()

Conclusion

I hope that this has been a useful introduction into the powerful connection which exists between the world of the web, HTML and PHP. Using this connection, you can start to build up truly complex websites. There are many more aspets of web development yet to learn, as well as a great deal more to do with PHP itself, but know that these very basic initial concepts are the very same that some of the most popular and massive sites on the internet are built on!

Later tutorials will deal with some of the more specific features of PHP outlined in the above tutorial, including variables and functions.

« Previous Next »

Robin Metcalfe is a freelance developer based in Edinburgh, Scotland with loads of experience in old and new web technologies. Want to know more?

He is currently available for hire . You can also get in touch via Twitter