What is PHP?




PHP Tutorial

Introduction

PHP is a scripting language primarily used for web development. It is an easy language to learn, and this has led to it becoming one of the most popular languages used today. PHP is usually the P in a LAMP stack. This is because pairing PHP with Linux, Apache, and MySQL is very common. The P can also stand for Python or Perl if they are used instead of PHP.

Linux (the L in LAMP) can be replaced with Windows (WAMP) or Mac OS X (MAMP). Since Windows is the most popular desktop operating system, we’ll be using a package called XAMPP for our developing/testing environment. XAMPP is a complete, easy to install version of Apache, MySQL, and PHP, which can be installed on Windows. Also note, there are versions of XAMPP for Linux and OS X as well. Before going any further with this PHP tutorial, please be sure to install and configure XAMPP by following the guide here as we’ll be referring to and using this setup for this tutorial.

What can I do with PHP?

This is one of the first questions you may find yourself asking. PHP is a versatile language. It can be used for many things, but its primary use is for server-side web scripting. What is server-side web scripting? PHP is a hypertext preprocessor. This means that it performs some processing before the web server delivers the hypertext (HTML) to the user’s browser. Let’s take a look at a typical web service request to examine this more closely.

First the user types a URL into their web browser’s address bar. For instance, they may type https://learningcomputer.com. The user’s computer asks its DNS server for the Internet Protocol (IP) address for this domain name. The DNS server responds with 64.14.68.19. Then the user’s computer knows the server address to use for its web request. It then sends an HTTP request to the server. The web server (Apache in this tutorial) will check the request to see what document the user is requesting. The web server looks for the document root for learningcomputer.com, and since there was no additional document name supplied, it uses the default document. If the user had typed something like – and press enter, the web server would look at its configuration to determine what to display for this URL. In the case of blog/category/google, the web server uses URL rewrite rules, which most likely causes something to occur in blog/index.php. We won’t go into this at the moment, but the important thing to remember is that the web server does the initially processing of the request to find out what the user wants to view.

Nothing has been sent to the user’s browser yet. If the user is requesting a PHP page, then PHP will take over the request. After PHP has completed the preprocessing, the final HTML, Javascript, and CSS are delivered to the user’s browser.

Editing PHP

It may be better to see all of this in action. This will help you to understand the meaning of preprocessor. To get started in PHP you must have your web server installed and running. Refer to the XAMPP installation link above if you haven’t done so already. Make sure that you start Apache and MySQL from the XAMPP Control Panel.

Next, you’ll need a text editor. PHP MUST be edited with a text editor. You cannot use a word processor. This is critical. Windows comes with a text editor called Notepad. This can be used for our tutorial, but I recommend Notepad++ as it is more feature rich. The one feature that standard Notepad lacks and I find essential is syntax highlighting. This helps us to see code more clearly, as it differentiates between various parts of the language. So, if you want to take advantage of the added features of Notepad++, download it here. I won’t walk you through the installation of Notepad++, but it is very straight-forward.

After downloading and installing Notepad++, start it up and get ready to start programming in PHP! Notepad++ may start with a document called change.log open. You can close it by clicking the red x in the right side of the document’s tab. You will then have a document called new 1 open. Let’s save this document as a PHP file so that we get the added bonus of syntax highlighting.

Click File -> Save As in the top menu.

what-is-php-programming1

Navigate to C:\xampp\htdocs, set the file name to index.php and then click Save.

We are using index.php because this is the default document used by Apache. Be aware that the default document configuration has an order of precedence. For instance, if there was a file named index.html in this same directory, it could also be used as a default document. By default document, I am referring to the default document the web server will return if no page name is provided. So, if you open up another tab or window in your web browser and type http://localhost, there is no document specified and the web server gives you the highest priority default document it has, which in our case should be index.php. However, index.php contains nothing, so the page is blank.

To show the idea of default document more clearly, in Notepad++ click File -> New. Next click File -> Save As to save this new document. Your save as dialog box should already have C:\xampp\htdocs selected as the location. If not, browse to that location. Change the file name to index.html and click Save.

Now, inside this index.html document type the following code.

<html>
<head>
<title>Test from index.html</title>
</head>
<body>
<h1>This is the index.html page</h1>
</body>
</html>

basic-html-code2

Notice that I’ve aligned the HTML to make it easier to read. Also note in Notepad++ the HTML tags are a different color than the text of the document. This is the syntax highlighting I referred to earlier.

Save the document by clicking File -> Save or by holding Ctrl and typing the S key (Ctrl + S). Refresh the page in your web browser. Notice that the page is still blank. XAMPP is using index.php as your default document. Type http://localhost/index.html into the address bar of your other web browser tab/window and hit enter. You should now see this:

what-is-php-index-page3

 

Specifying the document name of index.html tells the web server that you don’t want to see the default document (index.php). It then gives you the document you requested.

You can delete the index.html file as we won’t use it any longer. If Windows Explorer has extensions hidden you’ll want to make sure that the type of the file is HTML and not PHP before deleting it, since both files are named index. You could also delete both and recreate index.php. Once you’ve deleted index.html Notepad++ will report that the file no longer exists, and it will ask you if you want to keep it in the editor. Click No.

working-with-xampp-index-file4

You should be left with only the index.php file open and it should be blank.

Now, let’s try out some simple PHP. In the index.php file type the following:


<?php
echo “Hello from PHP!”;
?>

 

how-to-learn-php-programming5






 

Line 1 <?php tells the web server that it should treat the following code as PHP instead of HTML. This continues till it reaches the closing tag <b>?&gt;</b> at line 5. This should be used anytime you want to include PHP in your document. Note that the file must have a .php extension. There are other, less common PHP extensions but stick with this one for now. Just remember that if the file is named with an .html extension, the PHP code will not be processed correctly.

Line 3 contains the echo construct which is used to output a string of text. This text string can be enclosed in either single or double quotes. As we’ll see later, single and double quotes behave differently, but for now which you use is not important. Line 3 also ends with a semi-colon. Semi-colons are required at the end of all PHP statement. Leaving it out will cause an error.</p> <p>

Save the document with the shortcut Ctrl + S. In your web browser change the address to http://localhost and press the enter key. You should see the following:

print-hello-with-php-code6

Congratulations! you’ve created your first PHP page. Notice that <?php, echo, and ?> are not displayed on the web page. This demonstrates how the preprocessor works. The code within the <?php and ?> tags is executed on the server before the HTML is delivered to the browser. Let’s look at more PHP basics.

Variables and Data

Data-driven web applications are the most common usage for PHP. You may have data stored in a database that you want to show your users. A user may provide data in a web form for your application to process. Data is everywhere in a web application. PHP, like most other languages, tracks data by using named variables. Let’s see how variables work.

$firstname = “John”;

This statement sets the variable $firstname. We are assigning it the value “John” which is a string of text. Strings are enclosed in double or single quotes. In a lot of other languages, the first step would be to declare the variable and give it a type. For instance, in Java we would have to do this:

String firstname = “John”;

In PHP, we don’t declare the variable’s type. It is a loosely-typed language. The language is also dynamically typed, meaning that we could do this:

$firstname = 4;

We have assigned the number four to the variable. You should be cautious of dynamic typing because later on you may expect $firstname to be a string and it now contains a number. PHP let this assignment take place without any warnings or errors. Other languages such as Java would complain that there is a type mismatch and that the variable can’t contain a number. It would give a compilation error and the application would fail to execute. In PHP, no such error would occur, and your code may behave as expected. Be wary of reassignments. You have to keep track of your variable’s type yourself. Some programmers use something called Hungarian Notation to help alleviate this issue. For example they may use something like this:

$strFirstname = “John”;

The str in the variable name is meant to remind programmers that this should be a string. You can name your variables however you want, but keep in mind that others may have to read your code later and they may not know what type a variable should contain. We won’t be using Hungarian Notation for this tutorial.

Variables in PHP begin with a dollar sign $. They can contain letters, numbers, and underscores. They are also case-sensitive. $firstname and $firstName are not the same variable. You assign variables with the equal sign =. Be aware that unlike Visual Basic where the equal sign is used as an assignment operator as well as a comparison operator, in PHP it is only used for assignment. We’ll look at comparison operators later.



Let’s change the code in our index.php and see variables in actions. Replace the file contents of index.php with:


<?php>
$firstname = “John”;
echo $firstname;
?>

learning-php-7

Save the file and refresh your web browser tab/window

(http://localhost).

 

how-to-do-echo-php8

We set the variable $firstname to the string “John” and echoed it. Let’s modify the PHP file to contain standard HTML as well. Replace the file contents with the following:

<?php
$firstname = “John”;
?>
<html>
<head><title>Testing PHP</title></head>
<body>
<h1>
<?php
echo $firstname;
?>
</h1>
</body>
</html>

what-is-php-and-mysql9

Save and refresh your browser.

insert-php-script-in-html10

It’s also useful to look at the output source code that your browser is getting from the web server. Here is the source code you will see if you right-click in the browser window and choose View Source (varies from browser to browser).

using-php-editor-w-xampp11
Notice that you don’t see <?php, ?>, or echo.

Also notice, in our editor, that we have two sets of <?php ?> blocks. One at the beginning of the file where we set the variable and another within the <h1></h1> tag to echo the variable. You can embed PHP within any HTML and as many times as needed.

So far you may be wondering how to do something useful with PHP. Everything we’ve done so far could have been accomplished faster with plain HTML. PHP allows us to have dynamic content. For instance, instead of manually setting the $firstname variable to “John” we could have pulled the user’s first name from a database and displayed “Welcome, John!” instead. We can also do something many times.

Iteration

In programming, it’s often useful to do something more than once. This is called iteration, and PHP includes many different ways to iterate in the form of loops. The most common loop is the “for” loop. Here is an example:

for($i = 0; $i < 10; $i++) {
// do something
}

Let’s break this down. $i = 0 gives us an “index” variable used for counting the number of times the loop is executed. This variable could be named anything. $i is only used here because it is a common practice to name the index variable i or in PHP’s case $i. Next we see $i < 10. Notice that there is a semi-colon between these two statements. That’s required. $i < 10 says, while $i is less than 10, do everything in the “for” loop body over and over again. Next, we see $i++. This means to increment the value of $i after each iteration. The body of the loop is enclosed in curly braces {}. There’s one last concept I’d like to introduce here. The line that says:

// do something

This is a comment. It is ignored by PHP. Comments are useful for documenting your code, telling yourself and others what the code does. This is a single line comment and it starts with two forward-slashes. You can also comment multiple lines by using /* */ like so:

/*
This is a multi-line comment.
It is common to use these for file headers and function/method documentation.
*/

Let’s see the “for loop” in action by modifying our existing code a bit:

<?php
$firstname = “John”;
?>
<html>
<head><title>Testing PHP</title></head>
<body>
<?php
for($i = 0; $i < 10; $i++) {
echo “<p>$i. $firstname</p>”;
}
?>
</body>
</html>

do while loop visual basic

Save the file and refresh your browser tab/window.

You should see something like the following:

using-php-editor-w-xampp11

You may never need to repeat the name “John” ten times, but this concept is very useful. $i starts as 0 and every time the loop is executed we increment $i. It becomes 1, 2, 3, etc. You may be wondering why we started with zero and not one. The main reason for this is that a lot of times when you utilize a “for” loop you’ll be looping through an array. Arrays use zero-based indexes, meaning that the first index of an array is zero. We won’t be covering arrays in this tutorial, but it’s a good habit to use zero for your initial value. What if you wanted to display the numbering starting with one?

Let’s look at the echo line again.


echo “<p>$i. $firstname</p>”;

Now we’ll discuss the importance of single and double quotes. Notice in the above line of code we have double quotes surrounding everything after echo. PHP is echoing a number for $i and “John” for $firstname. Variables inside double quotes are evaluated for their value. Single quotes in this same situation would have a different result. If you change the double quotes to single quotes the output will look like this:

 

using-php-editor-w-xampp11

Instead of showing you the value of the variable, it literally echoes exactly what is inside the single quotes. What if you want to echo double quotes? You can either surround the double quotes with single quotes or you can escape the double quotes using a backslash character. Here is an examples of both.


echo �She said, “What\’s up?”‘;

Note that the quotes at the end, just before the semi-colon, are a double quote followed by a single quote.
This would output: She said, “What’s up?”

We enclosed everything in single quotes. So, the double quotes before the W and after the question mark will be echoed. The single quote/apostrophe in “What’s” would terminate the single quote. However, we prevented this by escaping it with a backslash character (\).

There are better ways to concatenate strings. We’ll look at those in a bit.
The “for” loop is probably the most commonly used loop in PHP. However, you should be aware that there are also “while” loops, “foreach” loops, and “do� while” loops. Each of these have their uses, and you should research them further.

Concatenation

The concatenation operator in PHP is a dot.


$myName = $firstname . ” Smith”;

This code would assign “John Smith” to the variable $myName. This is better than writing:


$myName = “$firstname Smith”;

Although it’s possible to output variable values by putting the variable in double quotes, I stay away from this as it can lead to errors. I almost exclusively use the concatenation operator when I need to combine two strings. You can also concatenate and assign at the same time.


$myName = $firstname;
$myName = ” Smith”;

Here we’ve assigned “John” to $myName. We then concatenate ” Smith” to the end of it by using the concatenate and assign operator (.=). This concatenates ” Smith” to the original value of $myName;

Conditionals

Now that you’ve learned how to make PHP do something more than once, you should learn how to make PHP decide things. Iterations and conditions are the two main parts of programming. Logically, we can do a lot of things with just these simple concepts.

What should I do?
How many times should I do it?

These are the logical concepts behind most computer code.
A condition is simply a decision.

Should I do this?
Should I do something else?

Let’s look at a simple PHP conditional.


if($myVariable == true) {
//do something
} else {
// do something else
}

You can read exactly what the code is doing. If my variable is true then do something. If it’s not true, we do something else. You could also check for multiple conditions like this:


if($myAge > 10) {
// do something
} else if($myAge < 10) {
// do this other thing
} else {
// do this only if the others aren’t true
}

For this code we have an if, else if, and an else block. Let’s pretend for a moment that the variable $myAge is equal to 10. The if ($myAge >10) statement will evaluate to false because 10 is not greater than 10. The code in the {} after the if condition is not executed. The else if statement will also evaluate to false because 10 is not less than 10. The code in the {} is not executed. Since neither of these are true the code within the {} after the else statement gets executed.

If you have many conditions to check, instead of writing a lot of else if statements, you could utilize a “switch/case” statement, but we won’t go into that in this tutorial.

Conclusion

We’ve only brushed the surface of what PHP can do. We’ve learned many basic programming concepts, and how these concepts are used specifically in PHP. Experiment with these concepts and research other aspects of PHP programming to learn more intermediate and advanced programming techniques. The official PHP documentation is a great reference point. You can find it here.

PHP Related Links:

PHP – Codecademy

Beginners PHP Tutorials

Learning PHP – About.com

Learn PHP the easy way – PHPBuddy.com

 






Connect with US!

Our YouTube channel