Beginning PHP

Workshop Requirements

Before beginning this workshop ensure that you have the facility to upload PHP files to a PHP enabled webserver. See Setting Up a Development Server for details of running a personal service if none other is available. You should also have some experience of HTML coding.

What is PHP?

PHP is what is known as a Server-Side Scripting Language - which means that it is interpreted on the web server before the webpage is sent to a web browser to be displayed. This can be seen in the expanded PHP recursive acronym PHP-Hypertext Pre-processor. This diagram outlines the process of how PHP interacts with a MySQL database.

PHP Diagram

A person using their web browser asks for a dynamic PHP webpage, the webserver has been configured to recognise the .php extension and passes the file to the PHP interpreter which in turn passes an SQL query to the MySQL server returning results for PHP to display. You can also use the PHP script to output HTML around the results to ensure that the results are formatted nicely for display within a browser. It is vital that the file has a .php extension or the web server will not know to pass it to the interpreter.

Getting Started

As stated above, the final output of any PHP file is usually normal HTML so it is often easiest to start with the basic HTML then start adding the dynamic PHP parts. So with that idea in mind create a new file called 'hello.php' with any text editor, add the following HTML and upload it to your php enabled webserver to preview the webpage (if you are using notepad it may call your file hello.php.txt - rename this file to hello.php before uploading the file):

<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>

You should check that this has worked by viewing the file in a browser of your choice. It is vital that you view the file from the server and not any local copy that you could open in the browser so that the PHP can be interpreted. We will now add our first piece of PHP code to generate the words 'Hello World' rather than have them coded within the HTML.

IMPORTANT: To distinguish the PHP parts from the normal HTML (which would get displayed as typed) and any PHP code (that we want interpreted) we use <?php and ?> which mean begin PHP code and end of PHP code. After the first instance of <?php on the page a shorthand <? will suffice.

We are now going to replace the static 'Hello World' in the HTML with a piece of PHP code that echoes the words instead. The 'echo' function is the easiest one to use in PHP and basically echoes anything within the quotes as output. Thus our first piece of PHP code would look like this:

<p><?php echo "Hello World"?></p>

....and when we integrate that code into our HTML we end up with...

<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<h4>Example One</h4>
<p><?php echo "Hello World"?></p>
</body>
</html>

Also note that after the echo command there is a semicolon to indicate that the line of PHP code is finished. Again save the file to your webspace, then preview it in a browser and you can see that the output should be the same as the first time. Congratulations - you have now made your first PHP script.

A Bit About Variables

Obviously the reason that we want to use PHP rather than normal static HTML is to allow us to use values that can change, or dynamic content from a database. These values are stored in variables that can then be echoed as part of the HTML as with 'Hello World' above. For those that haven't come across variables before, it is useful to think of a variable as an imaginary box into which any value may be placed so depending what we ask the database the value stored in the variable will be different. For those of you who have used variables in different contexts before, PHP (like PERL) doesn't require you to declare a variable (tell the interpreter that the variable exists and what type of variable it is) before using it.  PHP knows that something is a variable by the fact that the name is preceded with a dollar sign like so - $variable.

As a first example of a variable we will assign the words 'Hello World' to a variable and then echo that variable. So replace

<h4>Example One</h4>
<p><?php echo "Hello World"?></p>

with

<h4>Example Two</h4>
<?php
$firstvar 
"Hello World";
echo 
$firstvar;
?>

Again save the file, upload it to your webserver and preview the file in your browser (changing the Example number will help you see that the file is actually changing).

Numeric Variables

As well as containing what is known as a text string, a variable can also contain a numeric value:

<h4>Example Three</h4>
<?php
$firstvar 
5;
echo 
$firstvar;
?>

And when we assign a numeric value to a variable we can manipulate that variable as if it was a number. This is achieved by using operators much like we would in maths.

Operator Function
+ Add
- Subtract
* Multiply
/ Divide

For example to multiply the $firstvar by 2 and store that value in a $secondvar:

<h4>Example Four</h4>
<?php
$firstvar 
5;
$secondvar $firstvar 2;
echo 
$secondvar;
?>

Or if we just wanted to increase the value of $firstvar by 1:

<h4>Example Five</h4>
<?php
$firstvar 
5;
$firstvar $firstvar 1;
echo 
$firstvar;
?>

Reassigning the value of a variable to itself plus 1 can also be expressed like this:

<h4>Example Six</h4>
<?php
$firstvar 
5;
$firstvar += 1;
echo 
firstvar;
?>

If you want to do more than one calculation you can use brackets to separate the sections of the overall calculation. Bringing everything we've done so far to one line of PHP code, we can take a variable, add 1 to its value, multiply that new value by 2 and then store the new value in the original variable name.

<h4>Example Seven</h4>
<?php
$firstvar 
5;
$firstvar = ($firstvar 1) * 2;
echo 
$firstvar;
?>

Concatenating Text

You can add new text to a text string variable as well, although this process is called concatenation and uses a different operator to achieve this. To join two pieces of text together the '.' operator is used between each piece of text. This 'joining' can occur as part of assigning a value to a variable or as part of the echo function. Let's look at some examples.

To assign the word 'Hello' to $firstvar and add the word ' World' assigning the result to $secondvar (notice the space before 'World' is needed to preserve a space between the two words).

<h4>Example Eight</h4>
<?php
$firstvar 
"Hello";
$secondvar $firstvar " World";
echo(
$secondvar);
?>

To join two words as part of the echo function.

<h4>Example Nine</h4>
<?php
echo "Hello" " World";
?>

Or to join the $firstvar to the word 'World' as part of the echo function.

<h4>Example Ten</h4>
<?php
$firstvar 
"Hello";
echo 
$firstvar " World";
?>

Thus we have seen the main ways in which a variable can be manipulated.

Arrays

An array is simply a list of values. Each value can be retrieved independently of one another and can also be changed without affecting the other values. Like most things it's better to learn by seeing examples.

Creating An Array

An array can be created empty before any data is entered, but the more common way is to create an array and adding values at the same time. This is done in a similar way to assigning a variable value except we can use the array() function to specify the list of values:

<?php
$firstarray 
= array("Hello","World"); 
?>

An array can also be initialised without the array function simply byadding values. Note the square brackets [] are used to reference individual values in the array as we'll see in a moment.

<?php
$firstarray
[] = "Hello";
$firstarray[] = "World"
?>

These values can now be echoed as well, by using a number to identify (in the order in which they were entered) the values within the square brackets.

<h4>Example Eleven</h4>
<?php
$firstarray
[] = "Hello";
$firstarray[] = "World"
echo 
$firstarray[0] . " " $firstarray[1];
?>

Note: In the above example we have also concatenated the text with a space in between the words.  This is better than adding a space as part of the variable, either before or after one of the words, as we may wish to use the variables in a different order which would make the positioning of the space incorrect when all the variables were echoed.

You can then add other values to the array and echo those as well.

<h4>Example Twelve</h4> 
<?php
$firstarray
[] = "Hello";
$firstarray[] = "World"
echo 
$firstarray[0] . " " $firstarray[1];
$firstarray[] = "How";
$firstarray[] = "Are";
$firstarray[] = "You";
echo 
" " $firstarray[2] . " " $firstarray[3]. " " $firstarray[4];
?>

This type of simple array is very useful if you want to store and retrieve values of the same type, but seeking specific information based on a number can be a bit tricky, so it's sometimes better to use an associative array

Associative Arrays

With this type of array we store a label or key as well as a value that can be retrieved. These Key/Value pairs can again be created in two ways; by using the array() function, or directly assigning a value. This differs from the examples above as we're specifying two things this time. The key is specified and then the value like so:

key => value

To illustrate this lets create a capital city array where the Values will be the cities and the the countries are the Keys.

<h4>Example Thirteen</h4> 
<?php

$cities 
= array(
    
'france' => 'paris',
    
'germany' => 'berlin',
    
'uk' => 'london'
);
?>

We can echo these values by using the Key name in place of a number.

<h4>Example Thirteen</h4> 
<?php
$cities 
= array (
    
'france' => 'paris',
    
'germany' => 'berlin',
    
'uk' => 'london'
);
echo 
$cities['france'] . " " $cities['germany'] . " " $cities['uk']; 
?>

We could again do this without the array() function and just assign Key/Value pairs to the array.

<h4>Example Fourteen</h4> 
<?php
$cities
['france'] = 'paris';
$cities['germany'] = 'berlin';
$cities['uk'] = 'london';
echo 
$cities['france'] . " " $cities['germany'] . " " $cities['uk']; 
?>

The final thing to mention about arrays is that we can change a value of individual array members by manipulating those members the same way as with the variables.

<h4>Example Fifteen</h4> 
<?php
$math_array
['total'] = 0;
$math_array['one'] = 1;
$math_array['five'] = 5;
$math_array['eight'] = 8;
echo 
$math_array['one'] . "+" $math_array['five'] . "+" $math_array['eight'];
$math_array['total'] = ($math_array['one'] + $math_array['five'] + $math_array['eight']);
echo 
"=" $math_array['total'];
?>

Predefined Variables

So far we have used variables to which we have assigned values, but there are also several predefined variables that exist within PHP that hold values about the server environment. The naming conventions for these 'Superglobals' (so called due to their persistent presence) has changed with recent releases of PHP. These Virtual Workshops will use the type seen in PHP 4.2.0 and above. In earlier PHP releases it was possible to access the values stored in these variables by preceding the variable name with a $. For example to get the host name of the server we would use $SERVER_NAME. Now we have to do things slightly differently as these values are stored in global associative arrays instead. The important arrays that we will use straight away in these workshops are:

$_SERVER - Values set by the webserver such as SERVER_NAME or DOCUMENT_ROOT

$_GET - Variables provided as part of http get (such as those passed to the script in a URL).

$_POST - Variables provided as part of http post (such as those from an HTML form).

$_REQUEST - Stores all array members of $_POST and $_GET (and $_COOKIES).

Some Quick Examples

As this is a PHP page we can echo some of these variables here:

$_SERVER['SERVER_NAME']:- // which is the name of the server

$_SERVER['SCRIPT_NAME']:- //which is the name of this file

$_SERVER['REMOTE_ADDR'']:- //which is the IP address of your machine

$_SERVER['HTTP_USER_AGENT']:- //which is the web broswer you are using

At this point we won't concern ourselves with how these can be used, just to know that they exist is fine.

Conclusion

This first PHP Virtual Workshop has introduced a few basic concepts that will allow us to start to understand how PHP works and will be useful when we start building our web-based database in later parts. Understanding variables and arrays is the cornerstone of all dynamic web processing, so make sure that you understand fully what has gone one here before continuing. If you have any questions you can post a comment below or e-mail me directly.

Further Reading

 

In this section

Related Reading

Related Books

Learnging PHP

Related Ads