Up until recently, scripting on the internet was something which very few people even attempted, let alone
mastered.
Recently though, more and more people have been building their own websites and scripting languages
have become more important.
Because of this, scripting languages are becoming easier to learn and PHP is one
of the easiest and most powerful yet.
PHP stands for Hypertext Preprocessor and is a server-side scripting language. This means that the script is
run on your web server, not on the user's browser, so you do not need to worry about compatibility issues.
PHP is an open-source language, and PHP.net is its command post,
with extensive reference material about the language. PHP.net has exceptional, deep information about
the language, but it can be a little cryptic for the newcomer.
You may be wondering why you should choose PHP over other languages such as Perl or even why you should learn a scripting language at all. I will deal with learning scripting languages first. Learning a scripting language, or even understanding one, can open up huge new possibilities for your website. Although you can download pre-made scripts from sites like Hot Scripts, these will often contain advertising for the author or will not do exactly what you want. With an understanding of a scripting language you can easily edit these scripts to do what you want, or even create your own scripts.
Using scripts on your website allows you to add many new "interactive" features like feedback forms, guestbooks, message boards, persist data in a database and even more advanced features like portal systems, content management, authenticate and track users, etc.
With these sort of things on your website you will find that it gives a more professional image. As well as this, anyone wanting to work in the site development industry will find that it is much easier to get a job if they know a server-side language.
As mentioned earlier, PHP is a server-side scripting language. This means that, although your users will not need to install new software, your web host will need to have PHP set up on their server. It should be listed as part of your package but if you don't know if it is installed you can find out using the first script on this tutorial. If your server does not support PHP you can ask your web host to install it for you as it is free to download and install. If you need a low cost web host which supports PHP I would recommend NearlyFreeSpeech.NET.
Writing PHP on your computer is actually very simple. You don't need any special software, except for a text editor (like Notepad on Windows), althout I recomend you to use an IDE like Eclipse PDT.
The code itself fits right inside a page's HTML, and like HTML it is made up of plain text.
PHP scripts are always enclosed in between two PHP tags. This tells your server to parse the information between them as PHP.
<?php
// PHP code in here...
?>
As with any programming language, comments are essential for maintainability. The most important point to remember is to explain WHY you are doing something, not WHAT you are doing.
If you are working on a script with someone else you must let them know what your code does and if you are distributing your script you will need to show people how to edit it. Even if you are the only one who will use your script it is useful to comment so that you can edit it at a later date.
In PHP there are two ways you can comment. One way is used for single line comments and the other is used mainly for comments that go over one line. A single line comment is written as follows:
// Your comment can go in here
Everything after the // will be ignored when the script is executed. You can even place these on
the end of another line:
echo "Hello $name"; // Welcome the user
Another way of commenting is by using multi-line comments:
/* The following piece of code will take the input the user gave and will check that it is valid before adding it to the database. */
Anything between the /* and the */ will be ignored.
The first PHP script you will be writing is very basic. All it will do is print out all the information about PHP on your server. Type the following code into your text editor/IDE:
<?php
phpinfo();
?>
As you can see this is actually just one line of code. It is a standard PHP function called phpinfo
which will tell the server to print out a standard table of information giving you information on the setup
of the server.
One other thing you should notice in this example is that the line ends in a semicolon. This is very important. As with many other scripting and programming languages nearly all lines are ended with a semicolon and if you miss it out you will get an error.
In order to get a PHP script working, the file must end in .php.
Like HTML, your files are saved as plain text.
Now that you have finished your script, save it as phpinfo.php and upload it to your
server in the normal way. Then, using your browser, point it to the URL of this script. If it has worked (and
if PHP is installed on your server) you should get a huge page full of the information about PHP on your server.
If your script doesn't work and a blank page displays, you have either mistyped your code or your server does not support this function (although I have not yet found a server that does not). If, instead of a page being displayed, you are prompted to download the file, PHP is not installed on your server and you should either search for a new web host provider or ask your current host to install PHP.
To output text in your PHP script is actually very simple. As with most other things in PHP, you can do it in a
variety of different ways. The main one you will be using, though, is echo. This function will
allow you to output text, variables or a combination of both.
The echo statement is used in the following way:
echo "Hello world!";
echo is the command and tells the script what to do and is followed by the information to be
printed. Because you are outputting text, the text is also enclosed inside quotation marks. Finally, as with
nearly every line in PHP, it must end with a semicolon. You would, of course, have to enclose this in
your standard PHP tags, resulting in the following code:
<?php
echo "Hello world!";
?>
Which will display Hello world! on the screen.
As with other programming languages, PHP allows you to define variables.
A variable is a container for holding one or more values. It is the means by which PHP stores information and
passes it along between documents and functions and such.
In PHP there are several variable types, but the most common is called String and can hold
any text and/or numbers.
All variables begin with a $ sign. To assign some string to a variable you would use the
following code:
$welcome_text = "Hello and welcome to my website.";
This is quite a simple line to understand, everything inside the quotation marks will be assigned to the variable. You must remember a few rules about variables though:
$Welcome_Text is not the same as $welcome_text.$4site = 'not yet'; // invalid, starts with a number $_4site = 'not yet'; // valid, starts with an underscore $täyte = 'mansikka'; // valid, 'ä' is (Extended) ASCII 228.
$user_id = 987;
To display a variable on the screen uses exactly the same code as to display text but in a slightly different form. The following code would display your welcome text:
$welcome_text = "Hello and welcome to my website."; echo $welcome_text;
As you can see, the only major difference is that you do not need the quotation marks when printing a variable.
It is possible to print a variable with the echo command surrounded by other text, you need to
either embed the variable name in a text with quotation marks or concatenate the string with a full stop when
you use single quotation marks.
$name = "John"; echo "Hello $name!"; echo 'Hello '.$name.'!';Both will print Hello John!.
Unfortunately, the output from your PHP programs is quite boring. Everything is just output in the browser's default font. It is very easy, though, to format your text using HTML and CSS. This is because, as PHP is a server side language, the code is executed before the page is sent to the browser. This means that only the resulting information from the script is sent, so in the example above the browser would just be sent the text:
Hello and welcome to my website.
This means, though, that you can include standard HTML markup in your scripts and strings. The only problem
with this is that many HTML tags require the " sign. You may notice that this will clash with the
quotation marks used to print your text. This results in the need to tell the script which quotes should be used
(the ones at the beginning and end of the output) and which ones should be ignored (the ones in the HTML code).
For this example I will change the text to the Georgia font in red. The HTML markup for this could be:
<span style="font-family: Georgia; color: red;"></span>
As you can see this code contains 2 quotation marks so would confuse the script. Because of this you must add a backslash before each quotation mark to make the PHP script ignore it. The code would change to:
<span style=\"font-family: Georgia; color: red;\"></span>
You can now include this in your echo statement:
echo "<span style=\"font-family: Georgia; color: red;\">Hello and welcome to my website.</span>";
which will make the browser display:
Hello and welcome to my website.
The resulting HTML markup outputted by PHP is:
<span style="font-family: Georgia; color: red;">Hello and welcome to my website.</span>";
This does make it quite difficult to output HTML code to the browser, but later in this tutorial I will show you another way of doing this, which can make it a bit easier.
Arrays are common to many programming languages. They are special variables which can hold more than one value, each stored in its own numbered "space" in the array. Arrays are extremely useful, especially when using loops.
Setting up an array is slightly different to setting up a normal variable. In this example I will set up an array with 5 names on it:
$names[0] = "John"; $names[1] = "Paul"; $names[2] = "Steven"; $names[3] = "George"; $names[4] = "David";
As you can see, the parts of an array are all numbered, starting from 0. To add a value to an array you must specify the location in the array by putting an index between the square brackets.
However, the easiest way to create an array is to use the array() function, which assigns a bunch
of values to your array at once. This produces exactly the same array as above:
$names = array("John", "Paul", "Steven", "George", "David");
If you simply want to display a complex data type like this in PHP for debugging, you can use the
print_r() command:
print_r($names);
Resulting in the output:
Array ( [0] => John [1] => Paul [2] => Steven [3] => George [4] => David )
An associative array is an abstract data type composed of a collection of keys and a collection of values, where each key is associated with one value:
$wamp = array(
'Operating System' => "Windows",
'Server' => "Apache",
'Database' => "MySQL",
'Language' => "PHP"
);
print_r($wamp);
Resulting in the output:
Array ( [Operating System] => Windows [Server] => Apache [Database] => MySQL [Language] => PHP )
Reading from an array is just the same as putting information in. All you have to do is to refer to the array and the index of the piece of data in the array.
Print the third name of the $names array:
echo "The third name is $names[2]";
Output: The third name is Steven
Print the language of the associative array:
echo "The language is $wamp[Language]";
Output: The language is PHP
if statements are used to compare two values and carry out different actions based on the results
of the test. if statements take the form if, then, and
else.
Basically the if part checks for a condition. If it is true, the then statement
is executed. If not, the else statement is executed.
if structureThe structure of an if statement is as follows:
if (something == something else) {
// then statement;
} else {
// else statement;
}
The most common use of an if statement is to compare a variable to another piece of text, number,
or any other variable. For instance:
if ($username == "webmaster")
would compare the contents of the variable to the text string. The then section of code will only
be executed if the variable is exactly the same as the contents inside the quotation marks, so if the variable
contained "Webmaster" or "WEBMASTER" it will return false.
then statementYou can now add a then statement:
if ($username == "webmaster") {
echo "Please enter your password below";
}
This will only display this text if the username is "webmaster". If not, nothing will be displayed. You
can actually leave an if statement like this, as there is no actual requirement to have an
else part. This is especially useful if you are using multiple if statements.
else statement
Adding the else statement is just as easy as adding the then statement.
Just add some extra code:
if ($username == "webmaster") {
echo "Please enter your password below";
} else {
echo "We are sorry but you are not a recognised user";
}
Of course, you are not limited to just one line of code. You can add any PHP commands in between the curly
brackets. You can even include others if statments (nested statements).
There are other ways you can use your if statement to compare values. Firstly, you can compare two
different variables to see if their values match e.g:
if ($enteredpass == $password)
You can also use the standard comparison symbols to check to see if one variable is greater than or less than another:
if ($age < 13)
or
if ($date > $finished)
You can also check for multiple tests in one if statement. For instance, if you have a form and
you want to check if any of the fields were left blank you could use:
if ($name == "" || $email == "" || $password == "") {
echo "Please fill in all the fields";
}
or if you want to check that the fields are not empty:
if ($username != "" && $password != "") {
echo "You have fill all the fields";
}
| Example | Name | Result |
|---|---|---|
| $a == $b | Equal | TRUE if $a is equal to $b. |
| $a === $b | Identical | TRUE if $a is equal to $b and they are of the same type. |
| $a != $b | Not equal | TRUE if $a is not equal to $b. |
| $a <> $b | Not equal | TRUE if $a is not equal to $b. |
| $a !== $b | Not identical | TRUE if $a is not equal to $b or they are not of the same type. |
| $a < $b | Less than | TRUE if $a is strictly less than $b. |
| $a > $b | Greater than | TRUE if $a is strictly greater than $b. |
| $a <= $b | Less than or equal to | TRUE if $a is less than or equal to $b. |
| $a >= $b | Greater than or equal to | TRUE if $a is greater than or equal to $b. |
| Example | Name | Result |
|---|---|---|
| $a and $b | And | TRUE if both $a and $b are TRUE. |
| $a or $b | Or | TRUE if either $a or $b is TRUE. |
| $a xor $b | Xor | TRUE if either $a or $b is TRUE, but not both. |
| !$a | Not | TRUE if $a is not TRUE. |
| $a && $b | And | TRUE if both $a and $b are TRUE. |
| $a || $b | Or | TRUE if either $a or $b is TRUE. |
| Example | Name | Result |
|---|---|---|
| $a + $b | Addition | Sum of $a and $b. |
| $a - $b | Subtraction | Difference of $a and $b. |
| $a * $b | Multiplication | Product of $a and $b. |
| $a / $b | Division | Quotient of $a and $b. |
| $a % $b | Modulus | Remainder of $a divided by $b. |
A loop is a programming language construction that allows the programmer to instruct the computer to perform a certain instruction, or set of instructions over and over again.
while loop
The while loop is the simplest type of loop in PHP. It is also quite easy to set up and use.
A while loop will, as the name suggests, execute a piece of code until a certain condition is met.
The following example print the numbers 1 through 10:
$i = 1;
while ($i <= 10) {
echo $i++;
}
The while line tells the computer to repeat the code while $i is less than or equal
to 10. This is followed by the code to be executed which is enclosed between the curly brackets.
The increment $i++ does exactly the same as writing $i = $i + 1;.
It adds 1 to the value of $i each time the echo command is executed.
It continues being repeated until $i equals 10 when the computer will then move on to the next
part of the code.
for loop
The for loop is the most complex loop in PHP and require the evaluation of three different
expressions.
The following example print the numbers 1 through 10:
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
The first expression $i = 1 is evaluated once unconditionally at the beginning of the loop.
In the beginning of each iteration, $i <= 10 is evaluated. If it evaluates to true,
the loop continues and the nested statements are executed. If it evaluates to false, the execution
of the loop ends.
At the end of each iteration, $i++ is evaluated.
foreach loop
The foreach loop works only on arrays, and will issue an error when you try to use it on a
variable with a different data type or an uninitialized variable.
The following example print the numbers 1 through 10:
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($array as $value) {
echo $value;
}
On each loop, the value of the current element is assigned to $value and the internal array
pointer is advanced by one (so on the next loop, you'll be looking at the next element).
One of the best uses of a loop is to output the information in an array. For instance, if I want to print out the following list of names:
Name 1 is John
Name 2 is Paul
Name 3 is Steven
Name 4 is George
Name 5 is David
I could use the following code:
$number = 5;
$x = 0;
while ($x < $number) {
$namenumber = $x + 1;
echo "Name $namenumber is $names[$x]<br />";
++$x;
}
As you can see, I can use the variable $x from my loop to print out the names in the array. You
may have noticed I am also using the variable $namenumber which is always 1 greater than
$x. This is because the array numbering starts from 0, so to number the names correctly in the
output I must add one to the actual value.
The foreach loop has an useful extension to make it easier to loop over an associative array:
$wamp = array(
'Operating System' => "Windows",
'Server' => "Apache",
'Database' => "MySQL",
'Language' => "PHP"
);
foreach ($wamp as $key => $value) {
echo "The $key is $value<br />";
}
The Operating System is Windows
The Server is Apache
The Database is MySQL
The Language is PHP
On each loop, the key of the current element is assigned to $key and the value to
$value.
How to use PHP and forms together to make your PHP scripts useful. Example of a simple message box.
Setting up a form for use with a PHP script is exactly the same as a normal HTML page. As this is a PHP tutorial I will not go into depth on how to write your form but I will show you three of the main pieces of code you must know:
<input type="text" name="thebox" value="Your Name"/>
Will display a text input box with the string "Your Name" written in it as default. The value section of
this code is optional. The information defined by the attribute name will be the name of this text
box and should be unique.
<textarea name="message">Please write your message here.</textarea>
Will display a large scrolling text box with the text "Please write your message here." as default. Again, the name is defined and should be unique.
<input type="submit" value="Submit"/>
This will create a submit button for your form. You can change what it says on the button by changing the
button's value attribute.
All the elements for your form must be enclosed in a form tag:
<form action="process.php" method="get">
form elements, formatting, etc.
</form>
The form's action attribute tells what script to send data to (in this case it's
process.php). This can also be an absolute URL
(e.g. http://www.example.com/process.php).
The method attribute tells the form how to submit the data.
The next step is to get the data submitted the form into your script so that you can do something with it.
There are basically two different methods of getting the data into PHP, which depend on how they were submitted,
GET and POST, which can both be used by forms. You can submit data to a script
without a form using the GET method, by simply editing the URL.
The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For instance, you can create a script which shows different pages depending on the link that was clicked; page.php?user=david would show David's page and page.php?user=tom would show Tom's page, using the same script.
It is also possible to pass more than one piece of information to the script by separating parameters
with the & symbol: page.php?user=david&referrer=google&area=6, these
could all be accessed separately using the GET variables: user,
referrer and area.
To get a parameter which has been sent using the POST method use the following code:
$variablename = $_POST["variable"];
It takes the value from the POST parameter and assigns it to the variable $variablename.
Similarly, if you are using the GET method you should do:
$variablename = $_GET["variable"];
PHP has a library of canned functions that'll do everything from sorting stuff in alphabetical order to sending e-mails and connecting with databases, but you can also create your very own functions to do all manner of things related to your website. Functions you create are like little machines that do something for you. You construct them and then call them as needed.
Functions that you create are built with the function keyword:
function myFunction($value) {
echo $value;
}
and call it anywhere we want:
echo "Hello ";
myFunction("World!");
That results on Hello World!
mail function
One of the major uses of a server side scripting language is to provide a way of sending e-mails from the
server, and in particular, to take the form submitted data and output it to an e-mail address.
E-mail are extremely easy to send from PHP, there is actually just one command (i.e. mail()) for
sending e-mails.
mail($to, $subject, $body, $headers);
In this example I have used variables as arguments since they have descriptive names, but you could as well use plain text arguments.
| Argument | Description |
|---|---|
| $to | Contains the e-mail address to which the mail will be sent. |
| $subject | Section for the subject of the e-mail. |
| $body | The actual text of the e-mail. |
| $headers |
Used for any additional e-mail headers you may want to add. The most common use of this is the
from field of an e-mail, but you can also include other headers like
cc and bcc.
|
Before sending your mail, if you are using variables, you must set up the variable content beforehand. Here is some simple code for sending a message:
$from = "webmaster@example.com"; $to = "samaxes@example.com"; $subject = "PHP is easy!"; $body = "PHP is one of the best scripting languages around."; $headers = "From: $from\n"; mail($to, $subject, $body, $headers); echo "E-mail sent to $to";
This code will actually do two things:
Something you may have noticed from the example is that the from header ended with \n.
This is actually a very important character when sending an e-mail. It is the new line character and tells PHP
to take a new line in an e-mail. It is very important that this is put in after each header you add so that
your e-mail will follow the international standards in order to be delivered.
The \n character can also be used in the body section of the e-mail to put line breaks in, but
should never be used in the subject or the to field.
As anyone who has been scripting for a while will know, it is extremely easy to make mistakes in your code and
it is also very easy to input an invalid e-mail address.
Add this code snippet to check if the e-mail has been sent:
if (mail($to, $subject, $body, $headers)) {
echo "An e-mail was sent to $to with the subject: $subject";
} else {
echo "There was a problem sending the mail. Make sure that your e-mail address ($to) is valid.";
}
This code is self explanatory. If the mail was successfully sent it will output a success message, otherwise it will display an error with some suggestions to fix the problem.
Bringing it all together, we will now create a system to send user comment's by mail.
First, create an HTML page containing the form:
<form action="mail.php" method="post">
<p>Your Name: <input type="text" name="name" /></p>
<p>E-mail: <input type="text" name = "email" /></p>
<p>
Comments:<br />
<textarea name="comments"></textarea>
</p>
<p><input type="submit" value="Submit" /></p>
</form>
This will make a simple form where the user can enter their name, e-mail address and comments. You can of course add extra parts to this form, but remember to update the script too.
Now create the mail.php script:
<?php
$name = $_POST["name"];
$from = $_POST["email"];
$comments = $_POST["comments"];
$to = "samaxes@example.com";
$subject = "Comments From Your Site";
$body = "Name: $name.\nE-mail: $email.\n\nComments:\n$comments";
if (mail($to, $subject, $body, "From: $from\n")) {
echo "Thanks for your comments.";
} else {
echo "There was a problem sending the mail. Please check that the form is correctly filled.";
}
?>
You are now ready to fill in your comments and submit the form.
A very useful feature in PHP is that it allows you to alternate between PHP code and HTML markup.
<?php
// Top PHP code in here
?>
HTML Code
<?php
// Bottom PHP code in here
?>
This gets even better since the PHP execution will just continue from where it was left. Allowing you could do this:
<?php
if (if_condition) {
?>
HTML for IF being correct
<?php
} else {
?>
HTML for IF being wrong
<?php
}
?>
Always remember to close if and loops statements, though, it is very easy to forget.