PHP Basics
At this stage you will have either a hosting provider that has PHP installed or you have installed PHP on your own local machine and are ready to start working with PHP basics.
In this lesson we will cover the basics of PHP, how PHP scripts are structured and embedded into web pages. At the end of the lesson you will have a good understanding of the anatomy of a web pages and PHP scripts, how to write PHP code using the echo command and how that is output into a browser. We will also use the echo command to understand how to output strings and integers, and explore concatenation – something that will be very useful later when you want to construct outputs from difference sources. Let’s start at the very beginning with the anatomy of a web page.
Anatomy of a Web Page
To begin, let’s create a template file that we can reuse through out this course. This file will contain the necessary components required for a HTML page and we will use this a starting point for many of the files we will create during this course.
Take note!! Most code editors will display a line number for each line of your code, these line numbers are not part of your code but rather indicators so that you can refer to a specific part of your code – very useful if you have hundreds of lines of code. When we ask you to type in some code remember not to include the line numbers, just the code.
First, type the following code into a new file and save it as template.php using your preferred text editor (we recommend Notepad++ for windows or Textmate for Mac):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title></title> </head> <body> </body> </html>
If you are familiar with HTML you will recognise the two primary parts to this page, the head and the body. These are clearly identified by the HTML tags <head> and <body>. Note that the head start with an opening tag <head> and a closing tag </head>. The only difference between the two is a forward slash (/) in the closing tag. This is a standard within HTML. PHP also has opening and closing tags and we will discuss those a little later.
I find it useful to think of a HTML page as if it were a person. Just like a person there is a head and a body. Let’s take my friend Harry.
<HEAD>
Within Harry’s head are thoughts and feelings that are not usually seen by other people unless Harry chooses to share them. This “hidden” data can be a lit of different things from ideas and random thoughts to real numbers and plans that Harry may execute later.
Similarly, within a HTML page there is a head area that contains lines of code that might provide links to other resources or instructions, information and other data but nothing that is directly visible within a browser.
Both the hidden thoughts in Harry’s head and the hidden code within the head area of a HTML page often contain really important information for how other related things might look and behave. Not being able to see them does not make them any less important to Harry or our Web page.
<BODY>
On the other hand, Harry’s body is visible and I can see the jacket Harry is wearing, the way he walks and so on. These two parts of Harry are connected.
What we see on Harry’s body may have started in Harry’s head. For example Harry may have had a thought about jackets earlier today that may have resulted in him choosing this nice blue jacket.
This is very like a web page – the body area is where we put the visible parts of our page like tables and images, the parts that will be visible within a browser. These visible parts are likely to be influenced by code that exists in the head portion of our page. Perhaps it is a link to a style-sheet and an instruction about which character-set to use.
Anatomy of a PHP script
Like most elements within a web page, PHP scripts have an opening and closing tag that contain the code. Not unlike HTML, a PHP opening tag starts with a “<” character and a closing tag ends with a “>” character. Both opening and closing tags require a “?” character to identify that they are not HTML tag and the opening tag should contain the characters “PHP” to clearly identify which language the tags contain. The following is an example of how you might write PHP opening and closing tags:
<?php ?>
These tags do not contain any code, the white space separating the tags is where you will place your code ready to be executed by a web server’s PHP engine. A web page can contain different types of code. HTML is probably something that comes to mind when you think of a web page, and you would be right to think that a web page contains lots of HTML. But there can be other languages within a web page like ASP, PHP and JavaScript to mention a few. The web server needs to understand what language it is reading at any moment in time in order to correctly interpret what that code needs to do and we use PHP opening and closed tags to do that. Think of PHP tags as switches that the web server can use to switch modes from, say, HTML to PHP and back to HTML again. This allows us to embed PHP into HTML which makes PHP a very powerful development too for dynamic web pages.
One great feature of PHP is that, for the most part, while space does not matter. This means we can be flexible about how we arrange our code to help with legibility and visual presentation. As long as we observe the rules about how PHP is structured we can orgainise our code in virtually any way we like. One of the most important rules we need to remember is that each PHP command must end with a semicolon, this is a clear indicator to PHP that one command has finished and another is likely to begin. This is a great feature and means that we can be as flexible as we want when writing our code as long as we inform PHP when our commands start and finish.
Another import thing to remember is that PHP code needs to be contained within a file. Sounds obvious, but I did mention earlier that PHP and HTML work together so you might think that PHP is contained within a HTML file. That would be a mistake, you need to save your PHP (with or without HTML) in a file with a .php extension, NOT a .html or .htm extension. Once you save it as a .php file your web server will understand how to deal with it.
Writing Code
Now that we have some basics understood, let’s start writing some code.
First be sure that your files are located on a web server. If you are using WAMP this will be in the www directory. If you are using a hosting provider this will be located in a folder called public or www, or something along those lines – you will need to check which it is for you configuration.
Open template.php in your text editor and save it as basics.php. You now have 2 PHP files in your web directory. Now open the file (basics.php) in a browser window and you should see a large white space – essentially nothing to see which makes sense because we have not provided any instructions in the PHP file to display anything. Lets change that.
Locate the open <body> tag in your code and insert open and close PHP tags:
<body> <?php ?> </body>
Now let’s use some PHP to print some text on screen. Even though our page is saved as a PHP page (basics.php) it is very important that any PHP script within our page is contained within PHP tags – this is super important!! The PHP tags are the only way the server will know what type of code it is looking at as it scans through our page and it will need to switch on PHP to execute our code otherwise it will assume it is HTML.
The echo command
To print some text on screen we are going to use the echo command that will take some content and literally echo it onto the page:
<?php echo "This is my first piece of PHP code"; ?>
Save your file (basics.php) and refresh your browser – you should now see the text contained within the double quotes within your PHP code. This is your first fully functioning PHP script! Congratulations!!
Let’s have a closer look at that script to be sure we understand how it works.
The first thing to notice is the word echo. This is something called a language construct that behaves like a function (more about those in a later lesson). Echo has one job to do and that is to print whatever is between it and the semicolon that ends the statement. In this example, echo is printing a string, or a series of characters contained within quotation marks. Later you will see that echo can handle other data types and entities in addition to strings.
The last thing to notice about this echo statement, and this is true of every statement in PHP, is the semicolon (;). This single character is all PHP needs to know that a statement has finished and something else is about to begin. If you leave this out, PHP will simply keep reading code as a single statement until if comes to a semicolon or a close PHP tag. The golden rule is to always terminate PHP statements with a semicolon.
Browser Output
Let’s have a closer look at the web browser output. If you right-click on the web page and select view source from the menu you will see what the server actually output. We know that there was a PHP script in there and that it was using an echo to output some text, but look at what the source it telling us! There is no PHP there. It’s a page that is built entirely from HTML. So what happened to our PHP?
We know that all our PHP pages are located on the server, right? And we know that any PHP script within our pages must be clearly identified as PHP using those special opening and closing PHP tags, remember? We also know that the server takes our PHP code as it works through our page and executes any instructions that we have written – in this example an echo instruction to print some text on screen. Good so far? But this doesn’t explain where the rest of the PHP has gone when we look at the file in a browser. What actually happens is the server takes the entire PHP script, tags and all, executes all of the code within it and will return pure HTML, and only HTML, back to the page to be delivered to the browser.
So that’s where our PHP goes, that’s why we see absolutely no evidence of PHP in a PHP web page that has been correctly executed by a web server. We only see HTML an that is the way we want it. We only want HTML within a browser to ensure that it will function properly in any browser running on any operation system. The PHP code we might write and embed within our web pages may be simple and short like our echo, or complex and lengthy returning many values but at the end of the process we only want HTML returned to our client.
So now that we have a basic understanding of how the process works from script to server to browser let’s dig a little deeper into using echo.
Concatenation
We know how to output a single string using the echo command that will output the contents of double quotes (remembering to terminate the line with a semicolon). What if we want to output more than a single string, perhaps we want to output two strings next to each other. We can do that by concatenating two strings using a period symbol or a full stop.
Let’s add another echo to our earlier example, this time break the string into two parts and concatenate them using that special symbol:
<?php echo "This is my first piece of PHP code"; ?> <?php echo "This is my first" . " piece of PHP code"; ?>
Now if you refresh your browser you should see two identical strings. So the concatenation worked for the second string, it looks exactly the same as the first but there is a problem, it is not very legible, both strings are bunched up against each other and I think you would agree that they would look better if they were on different lines.
We can do that by inserting some HTML in to the string, after all the string (the characters within double quotes) is basically the same as HTML – it is just text that we will output onto the screen and we know that our PHP code will only deliver HTML to the browser.
Including HTML within an echo command
So how do we insert a new line in HTML? We could use a <br> tag, that will create a line break. We could also enclose our string in paragraph tags, or <p> </p>. Let’s keep it straight forward and use a <br> tag:
<?php echo "This is my first piece of PHP code<br>"; ?> <?php echo "This is my first" . " piece of PHP code<br>"; ?>
And here is the result. Both strings are on different lines in your browser.
So we can include HTML tags as well as text into our echo statements, and we can concatenate (or join) two or more strings is a single echo statement.
Later you will see that we can include a lot more types of data into our echo statements, even data drawn from different sources like databases or other scripts in different files. Let’s look at another example using another data type.
Including numbers within an echo command
Integers are a type of number, in a later lesson I will go into a lot of detail about data types but for now consider an integer a number. We can echo a number just as we can a string:
<?php echo 5; ?>
This will echo the digit 5. Try it.
We can also echo the result of a calculation:
<?php echo 5 + 5; ?>
This will echo the result of the sum of 5 + 5, which is 10. Try it for yourself.
Spend some time exploring with different numbers and strings to get more acquainted with the echo command.
Now that we are comfortable creating basic PHP code and displaying the results in a browser, in the next lesson we will look at what comments are, how we can create them and why we should use them – a lot!