PHP Basics

The Basics of PHP – Part 3

Welcome to part 3 of these basics of PHP tutorials. In this part, we are going to learn how to make if statements.

The syntax for an if statement look like this:

1
2
3
if (condition) {
     //Run this code if condition is true
}

Where it says “condition” we insert a Boolean expression, an expression that either has a value of true or false. If the condition is true, the code inside the brackets will be executed. Here’s an example:

1
2
3
if (3 > 2) {
     //This code would run because 3 is greater than 2
}

The Boolean expression 3>2 would return true, because 3 is greater than 2. Since it is true, the code inside the brackets would be executed. After the code in the brackets is executed, it would continue executing any code after the closing bracket.

Now consider this:

1
2
3
if (2 > 3) {
     //This code would not run because 2 is not greater than 3
}

The Boolean expression 2>3 would return false, because 2 is not greater than 3. Since it is false, the code inside the brackets would be skipped and any code after the ending bracket would continue on being executed.

Of course there are many other comparison operators besides > that you can use as well.

  • > returns true if the value to the left is greater than the value to the right.
  • >= returns true if the value to the left is greater than or equal to the value to the right
  • < returns true if the value to the left is less than the value to the right.
  • <= returns true if the value to the left if less than or equal to the value to the right.
  • == returns true if the value to the left is equal to the value to the right.
  • != returns true if the value to the left is not equal to the value to the right.

We can use variables for comparison as well.

1
2
3
if ($value == $value2) {
     print "$value equals $value2";
}

You can add another block of code called “else” that executes if the condition is not true.

1
2
3
4
5
if ($value == $value2) {
     print "$value equals $value2";
} else {
     print "$value does not equal $value2";
}

You can even add more blocks of code that execute if the initial condition statement is false, but another condition is true:

1
2
3
4
5
6
7
if ($value == $value2) {
     print "$value equals $value2";
} elseif ($value < $value2) {
     print "$value is less than $value2";
} else {
     print "$value is greater than $value2";
}

You can also combine multiple conditional statements into one.

1
2
3
4
5
if ($value == $value2 && $value2 == $value3) {
     print "$value, $value2, and $value3 are all equal"
} elseif ($value == $value2 || $value2 == $value3) {
     print "$value is equal to $value2 and/or $value2 is equal to $value3"
}

A statement consisting of two statements joined by && will only return true if both statements are true.
A statement consisting of two statements joined by || will return true if either of one of the two statement is true, or if both are true.

The Basics of PHP – Part #2

If you’re new to PHP make sure you to go back and read the first part of this tutorial before continuing.

In this tutorial we are going to learn about how to get data from an HTML form (inputted by a user) so that we can use that data in a PHP script.

There are two methods of getting data from HTML forms.  If you have browsed the web for any length of time before, you probably have seen the results of these methods in action.

The GET Method

When you see a URL that has a bunch of text and question marks and equal signs after the actual name of the file, they are using the GET method.  For example when you type in something on google and search you get a url like http://www.google.com/search?hl=en&q=AtomicPages+Hosting; that’s because they are using the GET method.  The part before the ? is the normal url to the page, but the part after that is actually passing data.  Each piece of data is made up of the name of the piece of data and the data itself (the value), separated by an equals sign.  Each pair of name and value pair is separated by an ampersand.  In the page http://www.google.com/search?hl=en&q=AtomicPages+Hosting there are 2 name/value pairs:

The first is named hl and has the value en.  In google’s case, they use this value to specify to the page which language you are searching in.  en stands for english.  If you leave that URL exactly as it is, except change it to say hl=fr, you’ll notice google will change to french.

The second name/value pair is called q and has a value of AtomicPages+Hosting.  This name/value pair is letting the page know what you typed in in the search box on the previous page, so that this page can display the results for that search.

Let’s do our own example of the GET method.  We will first make a simple HTML page called yourname.html containing just an ordinary HTML form.

<html>
<head>
<title>Your Name</title>
</head>
<body>
<form method="get" action="yourname_processor.php">
     Enter your First Name:<input type="text" name="fname" /><br />
     Enter your Last Name:<input type="text" name="lname" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Notice the method attribute of the form tag.  We set it to get so that the browser knows the use the GET method.  We also set the action to yourname_processor.php which will be the page that gets passed the input data that will we create next.  The browser will use the value of the name attribute in the input tags to name each input value.  So if somebody fills out this form with John as the first name and Smith as the last name, and presses the submit button they will be moved to a url that looks something like this: http://www.example.com/yourname_processor.php?fname=John&lname=Smith

In PHP you can get the value of variables submitted to the page with the GET method by using the name from the url, like so:

$_GET[name]

Let’s now make yourname_processor.php so that it displays the person’s name that they entered in yourname.html.

<html>
<head>
<title>Your Name</title>
</head>
<body>
<?php
     $firstname = $_GET['fname'];
     $lastname = $_GET['lname'];

     print "Your name is $firstname $lastname";
?>
</body>
</html>

This code takes the values from the get method and set’s them to variables called $firstname and $lastname.  Then it prints out these variables in a string, as we learned how to do in the previous tutorial

The POST Method

The code for the post method will look almost exactly the same as the GET.  The big difference is that in the POST method, the passed data won’t be displayed in the URL.  The data is passed secretly.  Let’s make the same example again using the POST method.

yourname.html would look like this:

<html>
<head>
<title>Your Name</title>
</head>
<body>
<form method="post" action="yourname_processor.php">
     Enter your First Name:<input type="text" name="fname" /><br />
     Enter your Last Name:<input type="text" name="lname" /><br />
     <input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

And yourname_processor.php would look like this:

<html>
<head>
<title>Your Name</title>
</head>
<body>
<?php
     $firstname = $_POST['fname'];
     $lastname = $_POST['lname'];

     print "Your name is $firstname $lastname";
?>
</body>
</html>

Unlike with GET, when you click the submit button on yourname.html you will be redirected to the exact same URL everytime, no matter what you entered.  The URL will always look like this http://www.example.com/yourname_processor.php with no name/value pairs on the end.  If you have ever pressed a back button on your browser and received a message that says something like “This page contains POST data, would you like to send the POST data again?”  This is because along with just sending you to this url, some data was also sent through the POST method.

GET vs. POST

There are pros and cons to both and they are both better to use in certain situations.  With GET method, the URL will be linkable and the data will be retained if somebody links you to the page.  With POST, if you try to link somebody to the page, the POST data won’t come with the link.

With POST however, data is kept more secure.  If you had somebody enter in a password, you would definitely want to use POST so that the password isn’t visible in the URL of the next page.

The Basics of PHP

PHP is a scripting language that is widely used on the web. If you know another programming language it’ll be a piece of cake. If not, you’re still in luck because it’s pretty easy to learn.

What it does

PHP is a server-side language, meaning the actual PHP code is interpreted by the server, not by your local computer. A server with php installed will interpret the php code embedded within the html on any page with a .php file extension. When a user loads a php driven website, the server finds the php code within the normal html code and executes this code. When it’s finished, it is left with what looks like just a normal html document (except the .php file extension), which it then sends off to the users’ computer. As with any html file, the html is then interpreted by the web browser and displayed on the screen. In fact, your web browser has no idea whether it was a php generated page or not – it looks just the same.

Getting Started

As I noted before, PHP is embedded within normal html. So how does the server find the PHP code that it needs to execute? It looks for any pairs of opening and closing php tags and executes the code between them.

The opening PHP tag looks like this: and then closing php tag looks like this: ?>

If you didn’t include any php tags at all, the server would just treat it like a normal html document. In fact, you can change all the file extensions on your website from .htm and .html to .php with no problem whatsoever.

So let’s set up a basic html document:

1
2
3
4
5
6
7
<html>
<head>
<title>My Website</title>
</head>
<body>
</body>
</html>

Now let’s say we wanted to add some PHP inside of the two body tags. We need to add the opening and closing PHP tags in order to do this:

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title>My Website</title>
</head>
<body>
<?php
// PHP Code goes here
?>
</body>
</html>

In order for you to run PHP code, you’ll need web hosting or you can just install PHP on your own computer.

I like to edit PHP code in Adobe Dreamweaver, but this is costly and unnecessary. You can in fact edit PHP on any simple text editor like notepad on windows or textedit on mac. If you’d like syntax highlighting, you can download a free text editor like Notepad++ or Notepad2.

The Basics

Almost every line of PHP code ends with a semicolon, with a few exceptions that we’ll get to when the time comes.

Let’s start by just making a program that will “print” out a message into the body of the html document that says “Hello World”

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title></title>
</head>
<body>
<?php
print "Hello World";
?>
</body>
</html>

Here we used the print command. All this does is outputs whatever you want into the html document. Here we outputted the text “Hello World”. In this case we wanted to output a string (a series of characters) so we enclose the string in quotes. Single or double quotes will work in this case, but there are some differences that we’ll get to later.

If we view this page in a web browser, you’ll notice we now have a page that says “Hello World”. When viewing the page, go up to the view menu (this may vary between different web browsers) and choose “View Source” or “View Page Source”. Now you’ll see the code that was sent by the server to the browser. Notice that you don’t see the php anymore, and it just looks like a normal HTML document. The PHP code has been executed and is no longer there. Of course, this example is not at all practical, as we could have done the same thing with just some html, and no php.

From now on, I’m just going to assume you know the basic html structure and we’ll just work with the php code that goes inside the php tags.

We could also print out some numbers, which don’t need quotes like strings do:

1
print 50.43939;

Of course, we could also use quotes around this if we wanted to, as it is a series of characters (a string).

1
print "50.43939";

Variables

You’re probably thinking “I know what variables are, I use them in math all the time” and you’re right! You do know what they are! Unlike in math though, variables are not named with names like x and y. Instead, variable names always start with a $ followed by whatever you want to call it. For example, we could have a variable called $value.

Also a little different than in math, in php, the symbol = does not mean “is equal to” it means “is set to”. The equals sign in php takes whatever is on the right side of it, and sticks it into the variables on the left side of it. Let’s make a variable called $height and set it to 10.

1
$height = 10;

NOTE TO EXPERIENCED PROGRAMMERS: In PHP, you don’t need to declare variable type. Variable type is handled automatically.

Now let’s try printing out this variable into a page.

1
2
3
4
<?php
$height = 10;
print $height;
?>

Now when you view this page, you’ll see the output is 10. We set the variable height to 10 and then we printed it out into the html. Notice that php code is executed from the top down. If we tried to do something like this:

1
2
3
4
<?php
print $height;
$height = 10;
?>

Here printing out $height wouldn’t print 10, because it hasn’t been set to 10 yet.

We can also do some math on our variables:

1
2
3
4
5
6
<?php
$height = 10;
$width = 38;
$area = $height*$width;
print $area;
?>

Here we set a variable $height to 10 and variable $width to 38. We then set a variable called $area to the variable $height multiplied by $width. Then we print the $area variable. If you run this script you’ll see you get 380 outputted, which is 10 times 38. Here we used * to multiply. You can also use + to add, – to subtract, and / to divide.

But it doesn’t end there! Variables don’t have to only hold numbers, they can hold strings of text as well:

1
2
$firstname = "Jackson";
$lastname = "Hines";

Now we could print this out using the print function:

1
print "Your name is $firstname $lastname.";

This code will output “Your name is Jackson Hines.” This is a case where single quotes wouldn’t work. Single quotes interpret everything literally. If you tried single quotes on this example you would get out exactly what you put in: “Your name is $firstname $lastname.”