Embedding PHP - PHP QuickStart Guide (2015)

PHP QuickStart Guide (2015)

Chapter 5: Embedding PHP

Congratulations on making it this far! In this chapter you'll start using some of what you've been learning and will begin to write PHP code. If you've read the last 3 chapters, you should be just about ready to dive in.

PHP can be embedded in HTML code in several different ways. Developers can mix embedding methods within the same document, as needed. It's important to note that code can be embedded anywhere within a document, even inside the opening and closing brackets of an HTML tag. This allows developers to create conditional attributes for HTML elements within their documents, among other things.

PHP code is executed separately from HTML code and isn't subject to the rules of the HTML structure. That means that the PHP code can also be located anywhere within the document and can be written in separate documents and called with theincludeandrequire functions as needed within the HTML. In the latter cases, the code will be executed as if it resided within the current page, providing a way for functions or other blocks of PHP code to be made available to an entire site without the need to continually rewrite them.

PHP Document Naming

The examples we're about to create will be ready to run on a live web server. There's one more important consideration, and that's how the server recognizes a document that contains PHP code. The PHP code will need to be parsed by the PHP interpreter in order to run. Otherwise, it will be delivered to the browser as HTML and will probably create errors that will make the document unreadable.

Web servers differ in the way they recognize documents that contain executable code (programs). The standard method is to pass any document with a file name that ends in “.php” to the PHP interpreter. That's the standard we'll be using in this book. If you're unsure of how your web host handles PHP files, please contact your hosting company or consult their documentation.

Creating PHP Files

If you're already using a software application to create web pages, chances are you'll be able to use it to create PHP files. If not, you can use a text editor like NotePad, WordPad or Simple Text to write your code.

When saving files, many text editors automatically add a default file extension. The most commonly used is “.txt”. In some cases, that extension can't be replaced with “.php”. If your editor does this, simply save the “myfile.php.txt” and remove the “.txt” later, either on your computer or on the web server.

Embedded Code Examples

The following series of examples will demonstrate the most common ways to directly embed PHP code in an HTML document. In the first example, we'll show how a variable can be created anywhere in a document and used in the body:

<?php $myname = 'John Doe'; // variable declaration?>
<title>PHP Programming Example 1</title>
Hello, my name is <?php echo $myname; ?>.

In the preceding example, the PHP code is in boldtype for easy identification. As you can see, we've created a variable named “myname” and assigned it an initial value of “John Doe.” That operation will be performed even before the opening HTML tag is output. Within the body of the document, we've used theecho construct to output the value of the variable directly in line with a string of text being output to the browser.

Note: The blocks of PHP code are opened and closed separately. Starting and stopping PHP code in this way is a feature you'll learn to use to your advantage in many ways.

Note: In many cases, such as using PHP to manipulate browser cookies, the PHP code MUST be written before the opening HTML tag. It's also common to write complex functions at the top of the document to speed up output when the page starts to load to the browser.

Type the code above into your editor and save the file with the name “myfile.php” and upload it to the public folder on your hosting account. Open your browser and point it to (your web address)/myfile.php.

If everything is correctly typed and configured, your browser window should read, “Hello, my name is John Doe.” on your screen. If so, congratulations! You've just written and executed your first PHP program. There won't be any fancy formatting, but we'll get to that soon.

Note: If your web page doesn't perform as expected, carefully check your code, making sure you've entered all the semicolons, opening and closing tags, and other characters exactly the way they appear in the book. You may also need to verify that your file name is correct and ends in “.php”.

If you still have trouble getting the correct results after taking the steps above, check your hosting account to make sure that PHP is available and configured correctly. Don't continue with the following examples until this page works as described.

When your first PHP program runs correctly, you can move on to the next example.

As previously mentioned, there are multiple ways to embed PHP code in a document. In the example below, you'll see that the PHP code has been condensed into one block in the body of the document. You'll also notice that theecho statement now contains all of the text we want to output, enclosed in double quotes.

You may recall that by enclosing a string in double quotes, we tell the PHP interpreter that it should perform any operations found. The “$” character tells the interpreter to treat the text after it as a variable and output its current value, in this case, “John Doe.”

<html><head><title>PHP Programming Example 2</title></head>
$myname = 'John Doe'; // variable declaration
echo "Hello, my name is $myname.";

If you save this block of code as a PHP file and upload it to your account, you should see exactly the same results as the previous file when you open it in your browser. It's quite common to embed large blocks of PHP code in the HTML body.

It's also possible to embed HTML code within PHP code, in a manner of speaking. This can be very convenient for displaying HTML without the need to use complex echo statements. Here's an example using an if/else construct:

<?php if ($a == 1){ ?>
<a href=”page1.html”>Go to Page 1</a>
<?php } else { ?>
<strong>PLEASE SELECT A PAGE</strong>
<?php } ?>

Note that the PHP code in the example above is simply opened and closed at the beginning and ending brackets for the control structure. Since the PHP interpreter stops evaluating code between the closing and opening tags, the output to the browser in those areas will be sent as HTML.

Although the example above will work fine, this is one instance in which readability can be improved by using the alternate control structure syntax, as below:

<?php if ($a == 1): ?>
<a href=”page1.html”>Go to Page 1</a>
<?php else: ?>
<strong>PLEASE SELECT A PAGE</strong>
<?php endif; ?>

Using either of the methods above is extremely convenient when a PHP control structure is used to control large blocks of HTML code.

Up to now, we've used very basic code examples to give you a foothold on the process of programming in PHP. Now that you're familiar with the basics, we'll move on in the following chapters to create a useful PHP application to run on your website.