PHP Introduction
In this tutorial you will learn the basics of PHP including:
- How PHP may be incorporated in a page
- Basic if... else... constructs
- PHP variables
- Processing data entered into an HTML form
- Using a PHP 'here document'
- Outputting strings and variables with PHP
- What is PHP?
- PHP is a server side scripting language. The letters P-H-P stand for 'Hypertext Pre-Processor'. Being server side it does all it's work on the server, whereas javascript, being a client side scripting language, does all it's good stuff on the client's computer. It's free and easy to learn, using similar syntax to C and Perl.
- What is the current version of PHP?
- For up to date version information visit this site www.php.net. At the time of writing the version is 5.2.5.
- What do I need to run PHP?
- PHP is most commonly used in conjunction with the Apache webserver platform, but it can also work with Microsoft IIS. For personal use you will need a locally installed webserver. I recommend WampServer, an excellent, easy-to-install pack consisting of Apache, PHP and the database application MySQL. Most webhosts provide both PHP and MySQL as part of their hosting package options.
- What can PHP do?
- Being a server side scripting language PHP can be used to intelligently process requests for web pages. The PHP may then dynamically select the required elements to be returned in response to the request. A good example might be an online store. A visitor to the store may select a particular department. PHP may be used to process the request from the visitors browser to visit a particular department. The PHP script will select relevant products from the database and returns these to the requesting browser. At the same time, another visitor to the same online store is browsing another department. PHP will dynamically present them with the relevant product details retrieved from the database.
PHP In a Page
The server side PHP interpreter is invoked by the tag: <?php and stopped by the tag: ?> These are generally used to denote a block of PHP code. Some servers support the shorthand <? ?> if turned on, but it is safer to stick to <?php ?><html> <head> </head> <body> <p> This is a PHP file cos it contains some PHP: <?php echo "This is the PHP"; ?> </p> </body> </html>
This would need to be save with the file extension .php in order for the server to recognise that it needs to use its PHP interpreter.
PHP Form Processing
Lets dive straight in with something that PHP is commonly used for: processing data that has been input by a user. Typically an HTML form may be used to capture data from a user. When the user submits the form a PHP script is called to perform various functions such as validating user input, passing the data to a database and presenting a response message to the users screen.
EXERCISE
Follow this link to open a PHP file that will prompt you for your age: Basic PHP form test
Try entering 17, 25, 120 and view the messages that are returned.
How it Works
To see the code, right click on the link above and select 'Save As' to save to your computer. The PHP file may be opened with any text editor.
<?php
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo $_SERVER['phpsnippets/PHP_SELF']; ?>" method="post"?>
Enter your age: <input name="age" size="2"?>
<input type="submit" name="submit" value="Go"?>
</form?>
<?php
}
else {
$age = $_POST['age'];
if ($age > 100) {
echo 'You should be dead';
}
elseif ($age < 21) {
echo 'You\'re too young for this club, come back when you\'re a little older';
}
else{
echo 'You are just right...';}
}
?>
Here is a breakdown of the code and how it works:
- The script uses a PHP if... else... construct to determine whether the 'submit' button has been pressed.
- This line:
if (!isset($_POST['submit'])) {}uses the immensely useful isset() function. This simple function is used to test a variable to see if a value has yet been set.
The exclamation mark before it simply means 'not'. So the statement is saying: 'if something is not set'. - The 'something' that is being examined is
$_POST['submit']
The PHP variable $_POST[] is an array (note the square brackets) that is used to collect values from an HTML form with the method=“post”
- After the 'if' condition test we open a curly bracket. The code between the curly brackets is that which is executed if the condition is met. In this case, if the submit button has not been pressed then an HTML form is presented.
- Looking at the 'action' attribute of the form element you can see that it is set as follows:
action="<?php echo $_SERVER['phpsnippets/PHP_SELF']; ?>"
The PHP echo function is simply a way to ouput text to a browser. In this case it is used to set the 'action' attribute of the 'form' element.
Then we see another built in PHP variable: $_SERVER. This predefined variable is an array that contains information such as headers, paths and script locations. In this example it is used to refer to the file 'form_test.php' itself. - Next, we get to the 'else' part of our if... else... construct. If the test condition is not met (i.e. the submit button has actually been pressed) then we do things with the data that has been entered into the form. This line declares a PHP variable '$age' and allocated the value entered into the 'age' field in the form.
$age = $_POST['age'];
Notice how the predefined PHP $_POST[] array is used. - Next, we invoke another PHP if... else... construct to test and compare the user input. This time we are using an 'elseif...' in order to test for more than two conditions.
EXERCISE
Take a close look at the file: Basic PHP form test
- How have comments been implemented in this file?
- Which operators are used to carry out the age comparisons?
- Try introducing a conditional test that will detect a specific age (e.g. 50) and output an appropriate message.
PHP if.. else..
Let us review the if.. else.. decision making construct in PHP. The construct is actually made up of two parts: The 'if' statement and the 'else' statement. The 'if' statement tests for a certain condition and if that condition is met then the code between the following curly braces is executed:
<?php if (condition test) {code to be executed} ?>
In the following example the variable 'variable' is tested to see if it is equal to '50' and if it is then a certain message is output to the screen. Note that the equality operator is '=='.
<?php if ($variable==50) {echo "Variable is 50";} ?>
If the variable does not equal '50' then the echo statement is not executed. If we wanted to execute some alternative code should the variable equal a different value we would use an else statement as follows:
<?php if ($variable==50)
{echo "Variable is 50";}
else
{echo "Variable is not 50";}
?>
More complex decision making structures can be achieved by nesting if statements within one another.
PHP Variables
You will have noticed that variables in PHP are denoted using the '$' sign. We used some of PHPs inbuilt predefined variables to process our form fields in a previous example. Values may be assigned to variables using the assignment operator: '='.
<?php $variable = "something"; $number=14; ?>
PHP variable names must begin with an underscore or a letter. They must not start with a number and must not contain certain prohibited characters. PHP is case sensitive.
PHP Here Document
A 'here document' is a special form of string syntax used in PHP that enable long strings of characters to be rendered and displayed. Here is an example: Basic Here Document
Here is the code:
<?php echo <<<HERE <h2>Here We Go</h2> <p>This is from a here document</p> HERE; ?>
Everything between the <<<HERE and the HERE; is being processed by the 'echo' method. The word 'HERE' is simply chosen to denote this block of output. The closing statement must always be on its own line with no space before it.
Echo and Print Statements
Output to screen can be achieved in PHP using either the 'echo' function or the 'print' function. Both can be considered interchangeable.
Exercise
Take a look at this simple example of an echo function in use: Echo variables
How did each variable become presented from a new line?