PHP

An Introduction on Generating and Change Webpages Through User Interaction

IMPORTANT NOTE:
This tutorial assumes you have knowledges of HTML and programming in general (we compare to Java). PHP is a language that can do many things on its own, but its main function is to generate the HTML that you would see on a webpage. In this tutorial, we look at how PHP interacts with HTML, so if you haven't let learned HTML ... go learn it!


Now then...What is PHP? PHP actually stands for PHP Hypertext Preprocessor, which is one of those "recursive" definitions. The definition is as such because its basic functionality is to generate the HTML that you see on a webpage. Usually this interacts with MySQL which is a database system (see the MySQL page for more).

So one thing that's vastly different about PHP than Java is that it's not a compiled language - that is, you don't have to write code and compile it first before interacting with it. It's also not always object-oriented. That is, you don't always have a class - you can simply write the code you need.

Since you're familiar with Java, PHP is quite simple to learn. The syntax is very similar. One thing that makes it simpler, however, is that you don't need to specify variable types. In Java when you declare variables, you need to specify their type (i.e. int, double, String, boolean) but in PHP, all you have to do is set up the variable name and set it to whatever you want!

Suppose we want to create a number variable called "count" in Java that holds the value 3.
In Java we would write:

private int count = 3;

...but in PHP, all we write is:

$count = 3;

ALL variables in PHP start with the $ sign. That's just how it's done. You don't have to worry about specifying the variable type either. If you assign a variable to an integer, then the variable is automatically an integer. However you can rename it to another type - like if we wanted to set "count" to 3.2 now, that would be fine. You also don't have to worry about public and private variables in PHP either. Users of websites coded in PHP can't access the PHP variables to begin with. If you look at the source code for a webpage in PHP all you'll see is the HTML code that's generated!

 Part 1: PHP and HTML [back to top]

One of the main purposes of PHP is to generate HTML on a webpage via functions and parameters that specify exactly what should be on the page. So one thing that's valuable about PHP and HTML is that you can just have a simple function that you repeat over a few pages so you don't have to continually repeat code.

Think about it - let's say you have five pages on your website and they all have the same few bits of code that generate the <head> and the navigation buttons. Then suppose you want to change the name of one of the navigation buttons - in HTML you'd have to go through every page and change the name!
BUT if you had instead a call to a function "getHeader()" on those pages, you could simply change the HTML generated in the function IN ONE FILE and it will change all the pages that call the "getHeader()" function.

Let's start a new PHP page. To switch from HTML to PHP you have to use <?php to go into PHP mode and ?> to go to HTML mode.

To start our functions PHP page, type:

<?php

function getHeader() {

?>

So, the <?php says we're entering PHP mode and we're declaring a new function called "getHeader()." Then then ?> says we're entering HTML mode and we're going to type some HTML that will get generated when we call this method. We have one open bracket because all the HTML we will include now will be part of the method.

So now let's go ahead and type all that preliminary HTML code that needs to go on every page, like all the stuff in the <head> and any initial <body> stuff.

Then you close up the method through going back to PHP mode and adding a closing bracket:

<?php } ?>

How about adding a little complication. Let's pass this function a variable that will tell us what the page is that we're on. All you have to do is add a variable in the parenthesis - just like you would in Java.

function getHeader($page) {

Now, when you specify the <title> in the header of the page, you can "echo" this variable and that will put the page name in the title. Echo is almost like Java's System.out.println. Here's the syntax:

<head>
<title><?php echo $page; ?></title>
</head>

See, <?php gets us into PHP mode and then we "echo" the variable, close with a semi-colon because it's a statement (just as in Java) and then return to HTML mode with ?>

Simple.

NOW on our other pages, all we have to do is call this method! For our home page, we might write:

<?php

include_once("functions.php");
getHeader("Home");

?>

and when we view our home page, we will see that the title of the page is "Home." Note that we have added the line include_once("functions.php"); which tells the page that we need to reference the functions.php file because it has functions we need. Pretty straight forward. This line of code is the same as Java's import functions.java; or C++'s #include functions.c;

It's good practice to keep a separate PHP file called "functions.php" that will hold all the functions like getHeader() or getFooter(), etc. Then each of your pages will have to include the functions.php file and can simply call the functions you need. When you think about it, all the pages on your website will have the same headers and footers - and if one or two don't, then that's where parameters come in handy because you can use conditionals to check what page you're on - and if it's a certain page, generate something special.

 Part 2: The $_GET array [back to top]

The $_GET array can include basically any variable and value you want and each gets appended to the website address after a question mark and separated from each other by an &. For example, if you look at address bar when you click on pages on a PHP site - like Facebook for example - you might see something like:

http://www.facebook.com/profile.php?id=1&friend=2

This $_GET array includes the "id" and the "friend" and are referenced through: $_GET[ 'id' ] (which = 1) and $_GET[ 'friend' ] (which = 22).

This is useful for something like Facebook, where, if you notice, everyone's profile page is the SAME PAGE (profile.php) and all the information on the page is generated from the id number in the $_GET array! From that, you can access the MySQL database and select all the information about the user from their ID number.

You can put whatever you want in the $_GET array. After the page name, you add the question mark ? and then the name=value and the & sign between variables. For example:

profile.php?id=1&friend=22&sent=true

...yields three variables in the $_GET array: id, friend and sent

NOTE: Notice that when you reference variables in the $_GET array, you don't use the index of the array like you would normally. Like in Java, if you had an array called myArray and you wanted an item, you'd type myArray[3] to get the third value. But in PHP, each item in the $_GET array has a key and a value, which makes coding much easier because then you can get the value through referencing the key! So in the example above, a "key" would be 'id' or 'friend' or 'sent' and the values would be '1' or '22' or 'true.'

So now, given variables in your $_GET array, you can then determine other things on your page, such as a conditional that says <?php if (isset($_GET['sent'])) { ?> which says if there's a key in the $_GET array called 'sent' then...let's do something like print out a message that says "Message Sent!" or something.

 Part 3: The $_POST array [back to top]

Similar to the $_GET array, there's something called the $_POST array, which is used for FORMS. You've seen the HTML form tag <form method="post">, well with PHP all the inputs have names and they become variables when you write @ extract($_POST); which basically just extracts all the variables from the $_POST array and turns them into variables.

So if, in your form, you had one input called "email" and another called "name" then once you extracted the $_POST array, you would have a variable called $name that would equal whatever you wrote in that input field, and a variable called $email that would equal whatever you wrote in THAT input field. That's pretty straight forward.

So here's a sample of PHP and HTML with forms:

<?php if (isset($_POST["trySave"]) && ($_POST["trySave"]==1)) {
   @ extract($_POST);
   if ($name!="") echo $name;
   if ($email!="") echo $email;
}
?>

<form method="post" action="send.php">
<input type="hidden" name="trySave" value="1">
<input type="text" name="name" />
<input type="text" name="email" />
</form>

There are a few ways to test if you've submitted a form, but using a hidden input type is pretty good. In this example we've used a hidden input type called "trySave" that has the value '1' but only after you submit the form. So this should be pretty simple to understand. The PHP code on the top checks if the input "trySave" in the form is set and if it equals 1 (which it does). Then, if both of those conditions are true, it extracts all the variables from the $_POST array. If you entered something for the "name" field - thus, it's not blank - then it prints it. Same deal for the "email" field. That's it!

Something like this is the easiest way to get information from the user in a form and then translate the inputs into variables for use in other functions.

 Part 4: Loops and Arrays [back to top]

When you create an array in PHP, you don't have to specify its size like you would in Java. Here's the syntax:

$newArray = array();

PHP has a built in "function," if you will, called "array()" that just lets us know that our variable $newArray is an array. Arrays are basically a series of mappings from a key to a value. In Java, all the keys are the index values (integers). But in PHP, the keys can be either integers OR STRINGS. So for example, we could have:

$newArray["age"] = 20;
$newArray[2] = "eric";
It can be either!!!
Now, in order to add to our array, we simply define some index as a certain value:

$newArray[3] = "Hello";
$newArray[1] = 2;
$newArray[2] = array();
$newArray[2][3] = 4.2;

NOTE that the items in an array don't all have to be the same! You can have one item that's a String, another that's an integer, another that's a fraction, another that's an array in itself, etc.

Now say you want to cycle through an array. First off, to get the array length, the syntax is: count($newArray), not array.length like in Java. There are two great ways to do loops in PHP. The first is the for loop which you should be familiar with. The syntax for that is:

for($i=0;$i<count($newArray);$i++) {
   //do something with $newArray[$i];
}

But here's something that's much cooler. Say you have an array of friends' names or something, called $friends. You can say:

foreach($friends as $friend) {
   //do something with $friend
}

What this does is cycle through the $friends array and create a variable $friend that is basically equal to $friends[$i] if you were to use a for loop. Why is this better? Well you don't have to use a variable $i to cycle through! It's a lot simpler in general.

 Part 5: Other Fun Things [back to top]

Here's something nifty: a quick way to do a conditional without actually writing an "if" statement.

<?php echo (count($array)>0)?"array is bigger":"array is smaller";?>

This just poses the question: is the size of the array greater than 0? If it is, then the php prints "array is bigger." Otherwise it prints "array is smaller." Note the colon (:) in between both print options. Simple.

NOTE: if you want to append something to a string, the syntax is:

$test = "Hello";
$test.= " World.";

...$test now = "Hello World." The ".=" ("dot equals") syntax is very similar to the "+=" ("plus equals") syntax in Java.

Want to take a string and make an array from it? What if you have a string of your interests, say, and each interest is separated by a comma. You can split it up and create an array where each thing in the array is another interest. Here is the syntax:

$newarray = explode(",",$interests,-1);

This bit of code "explodes" the string $interests wherever there is a comma. Now, $newarray is an array where each part is another interest. So let's say $interests = "piano, magic, art." Then $newarray[0]=="piano", $newarray[1]=="magic", $newarray[2]=="art." Easy as pie.

Also, say you have a variable that represents a person's first and last name, like $name = "Eric Fisher." You can write:

$name_array = explode(" ",$name);

...and $name_array[0] is the first name. It split up the string where there was a space - which in this case was between the first and last name.

Want to replace something in a string?

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

This will set $onlyconsonants = "Hll Wrld f PHP" because it replaces anything found in "Hello World of PHP" that is part of the $vowels array with "", nothing.

Want to check if something is in an array?

$isInArray = in_array("a",$vowels);

...will return "true" is the character "a" is found in the $vowels array and "false" if not. (Though because "a" happens to be in the $vowels array, the variable $isInArray will be true.)

You can find lots of other interesting built-in-PHP functions from the PHP Manual: www.php.net/manual/en/.

 Part 6: Classes [back to top]

So, classes in PHP are somewhat similar to how it works in Java, with a few minor changes. For one thing, because there are no "public" and "private" items, you simply define a class by writing:

class AdventurePlayer {

You can also define instance variables like in Java except you don't need to specify public/private nor the variable type. You just write:

var $name;
var $location;
var $hitPoints;

The functions are also very similar. However anytime you reference an instance variable, you can't just write the variable name like you would in Java. You have to write:

$this->name;

So, $this references this class, then the arrow is a pointer to a function or variable of the class. Also notice that in this case we're pointing to the $name variable BUT there is no $ sign before the variable name! You don't need it in this case!

If you're writing a function, you can write:

function multiply($i,$j) {

Note that again you don't have to specify the variable types for the variables in the parameters, nor do you have to specify what kind of function this is like you would in Java. PHP makes things a lot easier.


Click here for some sample and helpful PHP code!