Turn on suggestions
Auto-suggest helps you quickly narrow down your search results by suggesting possible matches as you type.
Showing results for
A Beginners Guide to PHP
A Beginners Guide to PHP
Topic Options
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report to Moderator
- Plusnet Community
- :
- Library
- :
- A Beginners Guide to PHP
A Beginners Guide to PHP
23-03-2010
11:59 PM
Advanced hosting services for our Plusnet Residential and Business accounts are available from Pay As You Host - our hosting platform.
- Introduction
- Who is this guide written for?
- Starting with PHP - the basics
- How to use PHP with your CGI webspace
- Example 1 - PHP within HTML webpages
- Example 2 - Using PHP with simple MySQL database
- Example 3 - Dynamically create a colourful webpage
- Useful links
1. Introduction
PHP is a scripting language that you can use with your CGI webspace and MySQL services, to create dynamic webpages. What is the difference between normal "static" webpages and the dynamic webpages that PHP allows you to write? Dynamic webpages are created on-the-fly and can interact with your visitor, providing a more compelling web experience. PHP originally stood for Personal Home Page Tools - although developers today say that it stands for 'PHP Hypertext Preprocessor'.What are the benefits of PHP?
- It's fast, flexible and scalable.
- Easy to write, easy to debug.
- Offers lots of excellent documentation and help from the developer community.
- It's FREE!
[Top]
2. Who is this guide written for?
This guide is aimed at people with little or no programming experience, who may have created HTML webpages, and would like to learn how PHP could help them make more interesting webpages.What do you need to use PHP?
- A basic understanding of HTML, and some experience of creating webpages.
- You need to have your CGI space activated - check the status of your CGI space.
- FTP (File Transfer Protocol) program, just like the one you might use for uploading to your webspace.
- You may need a telnet client, which will allow you to interact with your CGI space.
Also beneficial
- Basic programming knowledge - This isn't required, but if you have any traditional programming experience it will make learning PHP a great deal easier.
- An active MySQL service. MySQL is a database system that allows you to store and retrieve data. It is not essential, but it compliments your PHP tools and really expands what you can do. Check the status of your MySQL service.
[Top]
3. PHP - the basics
The following are just a few examples. PHP is a full language with a huge number of commands and functions to allow you to do almost anything. These ground rules and example commands should give you an idea of how it works.a) PHP can be scripted or embedded.
PHP scriptsWritten entirely in PHP, this is effectively an application which is executed on the CGI server. Any HTML displayed on a webpage has to be 'echoed', so it is displayed onscreen.
PHP embedded
PHP code is written into the HTML of a page. This makes is very easy to create dynamic websites as you only need to use PHP for the elements that are dynamic.
On your CGI webspace both types of file need the file extension .php and must have their file permissions set to 755.
When the PHP interpreter reads your file, it looks to see if there is any PHP code in the text. PHP commands should be surrounded by start and end tags. The interpreter will treat any code inside these tags as PHP script.
You can see this in Example 1 - PHP within HTML webpages below, where the HTML tags are echoed.
b) PHP script tags
PHP lets you embed your code inside the webpage. The code is then executed when the page is viewed. These embedded PHP commands are enclosed within special start and end tags, like this:<html>
<head></head>
<body>These words are static. <br />
<?php
//print output
echo 'These words are generated using PHP';
?>
</body>
</html>
c) Semicolon
The semicolon ';' indicates the end of a PHP statement and should never be forgotten.d) Spaces
White spaces between PHP statements are ignored, just like with HTML. This allows you to arrange code so that it is easy to read and check, such as placing the opening and closing tags on their own lines (as in the code above).e) Variables
Allow computer programs to do things that are more interesting and useful than just sums. Variables can be words or numbers, to be stored, compared or output. In PHP, variable names start with a dollar sign ($) and must begin with a letter or underscore. optionally followed by more letters, numbers and/or underscores.<?php
//define variables
$Fruit = 'apples';
$class = 'fresh';
$cost = 1;
//print output
echo "We have <strong>$class $Fruit</strong> for sale at £$cost each.";
?>
Note that variable names in PHP are case sensitive.
Boolean - allow for logical values like "true" or "false"
<?php
$auth = true;
?>
Integer and Floating point - numbers
<?php
$domain = 52.88;
?>
Strings - sequences of characters
<?php
$what = "The rain in Spain,";
$where = "falls mainly on the plain.";
$sentence = "$what $where";
echo $sentence;
?>
f) Include Function
This is an example function that is really useful, and doesn't require a lot of in-depth PHP knowledge to make use of.Without understanding much about the details of PHP, you can save yourself a great deal of time with the use of the PHP include function. The include function takes a file name and simply inserts that file's contents into the script that uses the Include function.
<html>
<head></head>
<body>
<?php
include("menu.php");
?>
<p>This is a homepage that pulls in a common menu</p>
</body>
</html>
The file menu.php could contain a simple html menu that you wish to appear at the top of each page of your website. Whenever you wanted to update the menu, you would only need to change the menu.php file, which would automatically update on all the pages of your website.
g) Comments
Writing comments in your code can make debugging faster and easier.A single line comment in PHP script works with -
//this is a comment - it will be ignored by PHP
[Top]
4. How to use PHP with your CGI space
Whether you know the basics of PHP already or are just getting started, you will need to understand how PHP is used with our CGI (Common Gateway Interface) server to run PHP content on your site.Key points
- Files containing PHP must be stored in the your CGI space, not your regular webspace. They should not be put in the cgi-bin though.
- Upload all files containing PHP to your CGI webspace
- Upload PHP files in ASCII format.
- Set file permission to 755 for PHP files.
Calling a PHP script with no input from the web visitor
An ordinary link on your web page should work:<a href = "http://ccgi.username.plus.com/your_script_name.php">Run my script</a>
If you need to pass "fixed" values to the script, do:
<a href = "http://ccgi.username.plus.com/your_script_name.php?name=rosy&status=dozy">
Run my script with parameters</a>
Calling a PHP script with input from the web visitor
This can be done using the HTML form fields like this -<form action="http://ccgi.username.plus.com/your_script_name.php"
method = "post">
<input type="radio" name="option1" value="option1" checked>Option 1
<input type="radio" name="option2" value="option2">Option 2
<input type="submit" name="button" value="run my script with input from visitor">
<input type="reset" name="reset">
</form>
[Top]
5. Example 1 - PHP within HTML webpages
PHP can be treated as a CGI script as above, or embedded into an HTML webpage. Note that the shortened version of the PHP tag is used, which doesn't include the letters PHP. Note that not all server environments support the short version of the tag.<html>
<head>
<?php
// A comment can be inserted like this
// Here we designate some variables
$bgcolor = "green";
$textcolor = "white";
?>
<title>Another PHP example</title>
</head>
<body <?php print "bgcolor='$bgcolor' text='$textcolor'";?>>
<h3>Behold, a PHP enabled page :-)</h3>
</body>
</html>
- Create the above in a text editor and name it 'phpexample1.php'.
- Upload the file (in ASCII format) to your CGI webspace
- Set file permissions to 755.
- Enter http://ccgi.yourwebspace.address/phpexample1.php in your browser to see the result.
It's important to notice how the PHP and HTML code are different, and even more importantly how PHP outputs code (such as 'bgcolor') that ends up as HTML. However, this is only a very simple example of what PHP can do. If you look at the source of the web page produced in the above example you'll get:
<html>
<head>
<title>Another PHP example</title>
</head>
<body bgcolor='green' text='white'>
<h3>Behold, a PHP enabled page :-)</h3>
</body>
</html>
As you can see, the actual PHP scripting commands are not visible on the client side. The actual creation of the HTML page is done on the server itself.
[Top]
6. Example 2 - Using PHP with simple MySQL database
To help you get started, the example below shows how easy it is to get a PHP script online. Accessing databases is one of the main functions of PHP, a simple task that can be handled in 2 or 3 lines of code. There are built-in facilities in PHP to access a wide range of database solutions, such as MySQL, MSQL, Dbase and Oracle. If you are using your MySQL feature, then you'll most likely have received the following piece of code in your confirmation email (Script provided by Rosemary Powell).<?php
$db_host="host_name_here";
$username="userid_here";
$password="your_password_here";
$DB_name="your_dbname_here";
echo "<html><body>";
$chan = mysql_connect($db_host,$username,$password);
mysql_select_db($DB_name,$chan);
$resultid=mysql_query("select * from test",$chan);
while ($resultrow = mysql_fetch_row($resultid)) {
while (list($key,$value) = each($resultrow)) {
echo "$value";
}
echo "<br />";
}
echo "</body></html>";
?>
This example script allows you to easily test query your database and write the results to HTML, displaying the results 'dynamically' in your browser.
- Create a file based on the above in a text editor. Name it 'mydbtest.php'
- Edit the host name, user ID, password and database name to the details contained in your MySQL activation email.
- Save it as 'mydbtest.php'.
- Upload this PHP page from your computer into your CGI webspace in ASCII format.
- Set file permissions to 755, so that the file is executable.
- Call your page - your URL link is http://ccgi.yourwebspace.address/mydbtest.phpYou can link to this from one another page or just type it directly into a browser for testing.
[Top]
7. Example 3 - Dynamically create a colourful webpage
For the final page to try for yourself, here's an example of something more useful.<html><head><title>PHP Font Chart</title></head><body>
<table border="1" cellpadding="5" cellspacing="0">
<?php
for ($Red = 0; $Red <= 255; $Red +=51) {
for ($Green = 0; $Green <= 255; $Green +=51) {
print "<tr>\n";
for ($Blue = 0; $Blue <= 255; $Blue += 51) {
printf(" <td><font color=\"#%02X%02X%02X\">", $Red, $Green, $Blue);
printf("Font Colour: %02X%02X%02X</font></td>\n", $Red, $Green, $Blue);
}
print "</tr>\n";
}
}
?>
</table></body></html>
- Copy the above script into your text editor and save it as 'webcolours.php'
- Upload the file (in ASCII format) to your CGI webspace
- Set file permissions to 755.
- Enter http://ccgi.yourwebspace.address/webcolours.php in your browser to see the result.
This program prints out a table using the colours that display relatively similar in all web browsers across different Operating Systems (called Netsafe colours).
The program sets up an HTML page with three "FOR" loops, one for each of the red, green and blue colour elements.
The FOR loop is the most complex loop in PHP, it consists of three parts, or expressions:
FOR(expr1; expr2; expr3) statement
The first expression (expr1) is evaluated only once at the beginning of this section.
The second expression (expr2) is evaluated at the beginning of each iteration of the loop. If this expression evaluates to TRUE, the loop is gone through. If it evaluates as false, the loop is ended and the program will continue after the FOR loop.
At the end of each iteration, expr3 is evaluated (executed). Note: If expr2 is false, expr3 is not evaluated.
The most common use for such a loop is to run through a series of commands a number of times, in our example we use the FOR loop to cycle through the values of red, green and blue in 'nested' loops.
In our program we set expr1 in each of the loops to a variable ($Red, $Green, $Blue) which holds a decimal number representing a piece of our Netsafe colours (0, 51, 102, 153, 204, or 255).
In expr2 we compare our variable to see if it is greater than 255. If it is we exit the loop, if not we run the statements following the FOR loop and then evaluate expr3 which adds 51 to our variable using the "+=" operator.
For example, in our first FOR loop we have "$Red += 51" this literally means take the current value of $Red, add 51 to it and then assign it back to $Red. In addition to being more concise to write, PHP has been optimised to execute this particular command very quickly, so it will be quicker to run than the alternative command, which would be "$Red = $Red + 51".
The three loops together cycle through the 216 colours that will not show as dithered in a web browser. Each time the second loop is run it prints a table row. Each time the third loop is run it prints a table element which includes a font tag with a PHP formatted print statement:
printf(" <td><font color=\"#%02X%02X%02X\">", $Red, $Green, $Blue);
Printf allows us to output a formatted string consisting of our RGB variables.
The first part of the printf statement is the format specification to use. The remaining comma delimited portions are variables, strings or numbers to print out using the format specification. Notice that the specification string repeats itself three times ("%02X"), once for each variable that we are outputting.
The "%" marks the beginning of a format string. The next character is optional and says what character will be used to pad out the results to the right string length.
In our case we want all our hexadecimal values padded with 0, hence the "0" in our format string. The next number is a width specifier that says how many characters (minimum) this conversion should result in, in our case "2". Finally we have a type specifier that says what type of data should be used. In this case we want to convert our decimal numbers to hexadecimal. This is specified by using the "X" character.
Note also the use of "\n" - this is used to tell PHP to print a newline character. If you look at the source of the HTML code generated, you will see that this allows us to format the HTML code in a way which makes it straightforward to read.
[Top]
8. Useful links
There's so much that you can do with PHP it's difficult to know where to start. Here are just a few of the sites which will allow you to learn more about PHP and how to use it create your website:- http://www.php.net/
- http://www.zend.com/
- http://php.resourceindex.com/
- http://www.phpbuilder.com/
- http://www.hotscripts.com/PHP/
- http://www.webmonkey.com/webmonkey/programming/php/
[Top]