Sunday, July 8, 2007

Javascript Tutorial - Part 8

 

Introduction
In the last part I explained a few of the things you can do using forms. In this, the final part, of the JavaScript tutorial I will explain how you can do some other things with your JavaScript forms.
Using The Submit Button
The most common use of forms is to submit data to a script so that it can be processed. This is fine if you are using CGI to do a mailto form or something like that, but if you just want to run a piece of JavaScript from a form you will need to do things a little differently. The first part you must learn about is the return false; attribute. It can be used as follows:
<form name="myform" onSubmit="return false;">
<input type="submit" value="Submit">
</form>
You can try it out below:

What this code does is tell the JavaScript that when the form is submitted it should do nothing. This stops Netscape from refreshing the page (as it would do if there was just a submit button and the form had no action). Now what you can do is to call a function using the submit button:
<form name="myform" onSubmit="MyFunction(); return false;">
Which will tell the browser to run the function 'MyFunction' when the Submit button is clicked. You can, of course, use this without the:
return false;
part. This would be useful if, for example, you want to validate a form before it is sent to a CGI script. You would include the form's action as normal. Then, in the onSubmit part you would call your function to check what had been entered.
Checkboxes
Checkboxes and radio buttons are two of the remaining form items. First I will cover checkboxes.
Checkboxes have two possible values:
Unchecked Box
Checked Box
As there are only two possible values, the JavaScript to refer to a checkbox is slightly different to that of a text box. In the example below the checkbox has been given the name my_checkbox and is in the form example1.
if(window.document.example1.my_checkbox.checked=true)
{
alert('The box is checked!')
}
else
{
window.document.example1.my_checkbox.checked=true;
alert('The box was not checked so I have checked it!');
}
I will now explain what this code does. It will check the value of the checkbox. If the value is ture (which means the checkbox is checked) then it will display an alert box which will tell you the box is checked. If it is not checked it will check the box (put a checkmark in it) and tell you what it has done.
If, of course, you want to check or refer to the unchecked value of a checkbox the code would be:
window.document.example1.my_checkbox.checked=false;
Remember that, when refering to check boxes you do not need to inclose true or false in quotations.
As with all other form objects you can use onBlur, onChange and onFocus.
Radio Buttons
Radio buttons are usually found in groups like this:
Blue
Red
Green
Only one button in the group can be checked at a time. Radio buttons work in exactly the same way as a checkbox, having a .checked property which can either be true or false.
Selects and Menus
The two remaining form elements are selects and menus. I will cover menus first. Menus are drop down boxes with several options in them (they are mainly used for things like selecting your country on a form). Selects are really just menus with multiple lines and scrollbars. To show how they work I will show you a quick example of a menu in action and the code for it. For a select box I would just change the height propery. To see the example click here. The code used is below:
<form name="go" onSubmit="return false;">
<select name="select" onChange="window.document.location=window.document.go.select.value;">
<option value="#" selected>Please Select</option>
<option value="http://www.microsoft.com">Microsoft</option>
<option value="http://www.yahoo.com">Yahoo!</option>
<option value="http://www.gowansnet.com">Gowansnet</option>
</select>
</form>
What this code is doing is, when the select is changed it is telling the page in the browser to change its location to the value of the select box. The location of the document is accessed using:
window.document.location
As you can see, this is could be very useful, both for getting feedback from visitors and for redirecting them (as in the example above).

Javascript Tutorial - Part 8

Javascript Tutorial - Part 7

 

Introduction
In part 6 I showed you how to use If and loops. In this part I will show you how you can manipulate HTML forms with JavaScript to improve your website.
Changing The Value Of A Text Box
Before you can manipulate text boxes you must first know how to create a form and how to create a text box in HTML. I will quickly explain this.
Forms for JavaScript are slightly different to standard ones as they do not require any information or script to handle them. You can do everything by just giving the form a name (although later you may want to add the other information so that you can also have the form submitted):
<form name="formname">
</form>
In this form you can place a text box using:
<input type="text" name="boxname">
Once you have this you can create your first JavaScript to refer to a form:

Move the mouse over here to add some text to the box
This is done very easily using the onMouseOver property of the link. It can refer to the text box as follows:
window.document.example1.first_text.value='Hi there';
This tells the browser to put 'Hi there!' into the value of the item called 'first_text' in the form called 'example1'.
You can also do this with multiline text boxes. You can use
/n
to start a new line.
In this section, you have learnt the most important part of this lesson, how to refer to an item in a form.
Events
Just like links, you can set events for items in a form. They are:
onBlur - Happens when the cursor is moved out of the field
onFocus - Happens when the cursor is moved into the field
onChange - Happens when the field is changed and the cursor moves out of it
These are placed into the code as part of the form's item for example:
<input type="text" onBlur="dothis">
JavaScript Functions
JavaScript functions are very useful, and this seems an appropriate place to introduce them. They are pieces of JavaScript which can be declared at the top of your page and can then be referred to again and again in your code. You can even pass parameters to them and make them do different things.
Functions take the following form:
function functionname(parameters)
{
}
For a very basic function you need no parameters and it would be constructed like this (in the <head> of the document):
function sayhi()
{
alert(Hi there!);
}
Then, anywhere in the text you could place this:
<a href="#" onMouseOver="sayhi();">Say Hi</a>
Which would display the alert whenever the mosuse passed over it. Unless you are repeating something many times, though, this will not seem particularly useful. This is where parameters become useful.
Parameters
Parameters are a very useful part of functions. They allow you to pass data to the function when it is called. Here is an example:
function say(what)
{
alert(what);
}
in the head, then:
<a href="#" onMouseOver="say(hi);">Say Hi</a>
<a href="#" onMouseOver="say(bye);">Say Bye</a>
What this is doing is the information in the brackets is passed to the function. In the brackets of the function is the word 'what'. This is telling the JavaScript to assign the information in the brackets to the variable what (the same as var what='something';). You can even do this with multiple pieces of information by separating th
em by commas.
As you can see functions and parameters are very useful.

Javascript Tutorial - Part 7

Javascript Tutorial - Part 6

 

Introduction
In previous parts I have shown you how to declare a JavaScript, open windows and display information. In this part I will show you how to use two of JavaScripts most important functions, If and Loops.
If
The if function allows you to check to see if something is true or false. For example you could check to see if text entered by a user matches a piece of text you already have (like a password). To show if in action click here.
As you can see this could be very useful for many sites. The code is as follows:
var guess = prompt("Please guess a number between 1 and 10","");
if(guess == 5)
{
alert('Correct! I was thinking of 5');
}
else
{
alert('Wrong! I was thinking of 5');
}
This code is made up of three main parts. The first part which gets the guess from the user, you have used before. This is followed by:
if(guess ==5)
Which is quite self explanitary. It checks to see if the variable guess is equal to 5. The if statement is followed by:
{
alert('Correct! I was thinking of 5');
}
The important part of this is the curly brackets round the alert command. These contain the code which should be executed if the if statement returns 'true' (in this example if guess equals 5). The final part is the:
else
{
alert('Wrong! I was thinking of 5');
}
This tells the browser that if the if statement does not return 'true' (in this example if guess does not equal 5) to execute the code between the curly brackets.
Together this code makes up the if statement.
More If
There are other conditions you can test with the if statement. Firstly, as well as using numbers you can compare variables or text:
if(variable == variable)
if(variable == "some text")
As well as doing this you can check to see if one variable is greater than another, less than another or not the same as another:
if(variable < othervariable)
If variable is less than othervariable
if(variable > othervariable)
If variable is greater than othervariable
if(variable <= othervariable)
If variable is less than or equal to othervariable
if(variable >= othervariable)
If variable is greater than or equal to othervariable
if(variable != othervariable)
If variable is not equal to other variable
These can be very useful in your web pages. You can also check to see if two conditions are true before executing code using &&:
if(variable1 == variable2) && (variable1 < variable3)
This will only execute its code if variable1 is equal to variable2 and is less than variable3. You can also run the code if one of the conditions is true:
if(variable1 == variable2) || (variable1 < variable3)
This will only execute its code if variable 1 is equal to variable to or is less than variable3.
While Loops
While loops are pieces of code which will repeat until the condition is met. This is very useful for things like passwords when you want to keep asking the user until they get it correct. For example this code will repeat until the user enters the word 'hello':
var password = 'hello';
var input = prompt('Please enter the password', '');
while(input != password)
{
var input= prompt('Please enter the password''');
}
This will continuously loop the code inside the { } until the test input does not equal password is false (the password is correct).
For Loops
For loops are used to do something a set number of times. For example:
for(loop=0; loop < 11; loop++)
{
document.writeln(loop);
}
This will start by setting the variable loop to 0, it will then loop, adding one to the value each time (using the loop++ code) as long as loop is less than 11. They take the form:
for(starting value; test; increment)
These have many uses.

Javascript Tutorial - Part 6

Javascript Tutorial - Part 5

 

Introduction
In this part I will show you how to use link events, do image swaps and display things in the browser status bar.
Link Events
A link event is a different way of including JavaScript on your page. Instead of having <script> tags in your HTML you can set JavaScript that will only be executed when certain things happen.
There are three ways of executing some JavaScript code in a link. They are:
onClick
onMouseOver
onMouseOut
They can have many different uses but the most common is for image swaps (mouseover images).
onClick
onClick works in exactly the same way as a standard HTML link. It is executed when someone clicks on a link in a page. It is inserted as follows:
<a href="#" onClick="JavaScript Code">Click Here</a>
As you can see, one main difference is that the href of the link points to a #. This is nothing to do with the JavaScript, it just neabs that, instead of opening a new page, the link will not do anything. You could, of course, include a link in here and you would be able to open a new page AND execute some code at the same time. This can be useful if you want to change the content of more than one browser window or frame at the same time.
onMouseOver and onMouseOut
onMouseOver and onMouseOut work in exactly the same way as onClick except for one major difference with each.
onMouseOver, as the name suggests, will execut the code when the mouse passes over the link. The onMouseOver will execute a piece of code when the mouse moves away from the link. They are used in exactly the same way as onClick.
Rollover Images
This is one of the main ways of using link events. If you have not seen rollover images before, they are images (usually used on navigation bars like the one at the top of this page) and when the mouse moves over the link it changes the image which is displayed.
This is done using a combination of the onMouseOver and onMouseOut events. To explain - when the mouse passes over the link you want the image to change to the new image, when it moves away from the link, the old picture should be displayed again.
The first thing you must do is edit the <img> tag you use to insert the image you want to change. Instead of just having something like this:
<img src="home.gif" alt="Home">
you would have the following:
<img src="home.gif" alt="Home" name="home_button">
The name for the image could be anything and, like the window names from the last part, is used to refer to the image later on.
Now you have given a name to the image you are using you will want to create the rollover. The first thing you must do is create the image for the rollover and save it. Then create a link round the image. If you don't want to have a link on the image you can still do a rollover by specifying the href as # which will make the link do nothing eg:
<a href="#"></a>
The following code will make a mouseover on your image (assuming you inserted the image as shown above and called your mouseover image homeon.gif):
<a href="index.htm" onMouseOver="home_button.src='homeon.gif';" onMouseOut="home_button.src='home.gif';"><img src="home.gif" alt="Home" name="home_button" border="0"></a>
I will now explain this code:
Firstly you are creating a standard link to index.htm. Then you are telling the browser that when the mouse moves over the link the image with the name home_button will change to homeon.gif. Then you are telling it that when the mouse moves away from the link to change the image called home_button to home.gif. Finally you are inserting an image called home_button with an alt tag of 'Home' and no border round it.
If you have read the last part of the tutorial you will see t
hat onClick, onMouseOver and onMouseOut can be used with text links as well as images in exactly the same way as you did above. This, of course, means that you can create interesting effects by, when the mouse moves over an image, another image changes. This could be very useful for placing a description of a link on a page.
Status Bar
The status bar is the grey bar along the bottom of a web browser where information like, how much the page has loaded and the URL which a link is pointing to appears. You can make your own text apppear in the status bar using the JavaScript you already know using the following code:
window.status='Your Text In Here';
You can include this in standard code, onClick, onMouseOver or onMouseOut. This allows you to do things like display a description of a link when the mouse moves over it.

Javascript Tutorial - Part 5

Javascript Tutorial - Part 4

Introduction

In the last part I showed you how you can use JavaScript to prompt the user for information and how you can display HTML via JavaScript. In this part I will show you how you can create and manipulate browser windows using JavaScript.

Windows and HTML

Before learning how to create and manipulate windows in JavaScript, it is important to know how to create and manipulate them in HTML. The HTML manipulation is very basic but will also help you to understand how windows work in web browsers.

Firstly you must know the two ways of creating a link which opens in a separate window. The most common use is to have:

<a href="link.html" target="_blank">Click Here</a>

This is the standard HTML code for opening a new window with the page in it.

A less common way of opening a new window is to use:

<a href="link.html" target="mywindow">Click Here</a>

This will create a new window, just like the first set of code, but it will also name the window 'mywindow'. This means that you can then have:

<a href="page2.html" target="mywindow">Change the page</a>

which, when clicked, will change the page which appears in the window you opened.

Knowing about how a window name works is very important as you must understand it to use JavaScript windows effectively.

Opening A Window With JavaScript

The first thing you should learn to do with JavaScript is to do exactly the same thing with JavaScript as you could do with HTML. The JavaScript command used to open a window is:

window.open

For this to work, though, it requires two extra things. Firstly you will need to have some extra information so that the JavaScript knows how to open the window:

window.open('link.html','mywindow');

This means that a window called 'mywindow' will open with the page link.html in it, exactly like with the HTML code above.

This code can either used as part of your JavaScript code (for example if you included it in the JavaScript code in the <head> section of your page it would open when the page loaded) or can be used when a link is clicked. To do this you must use another JavaScript command called onclick.

I will give you more information about how this command works in a later part but for now all you really need to know is the following: In your standard HTML code include a link as follows:

<a href="#" onClick="window.open('link.html','mywindow');">Click Here</a>

As you can see this is just the same window.open command inside an HTML tag.

Manipulating The Window

The main reason of using JavaScript to manipulate windows, though, is because you can set many things on the window which you could never do with HTML. JavaScript allows you to use commands to decide which parts of the browser window appear. This is done using a third part of the window.open command. This is where you decide the window features:

window.open('link.html','mywindow','window features');

There are many things you can include here. For example if you wanted a window that only has a location bar and a status bar (the part at the bottom of the browser) then you would use the following code:

window.open('link.html','mywindow','location, status');

There are many different things you can include in your new window:
Feature Function
menubar The File, Edit etc. menus at the top of the browser will be shown
scrollbar This will show scrollbars at the side of the window if they are needed
width You can set the width of the window in pixels (see the next section)
height You can set the height of the window in pixels (see the next section)
toolbar This will display the browser toolbar with the Back, Stop, Refresh buttons etc.
location The location bar (where you type in URLs) will be displayed in the browser
resizable This will allow the window to be resized by the user
directories This will show the directories in Netscape browsers like 'Whats new' and 'Whats cool'


Examples Of Manipulating Windows

You may be a little confused by all these options so I will show you a few examples of opening a window in JavaScript:

This window will open with a location bar, toolbar and will be resizable:

window.open('window1.htm','the_first_window','location, toolbar, resizable');


This will open another page in this window:

window.open('window2.htm','thefirstwindow');


This will open a window 200 pixels wide and 300 pixels high. It is not resizable and has a status bar and will scroll if necessary. This is a very commonly used combination:

window.open('window1.htm','thesecondwindow','height=300,width=200,status,scrollbars');

Javascript Tutorial - Part 3

 

Introduction
In the last part I showed you how to display alert boxes and how to get information from the user. I also explained how variables work.
document.writeln
This command is very useful as it will output information to a web page. I will start with a basic example of how to use it:
document.writeln('Hello there!');
This basically tells the JavaScript to write to the document (web page) on a new line the text Hello there!. The really useful bit of this is that you can tell the JavaScript to output text, HTML and variables. First of all I will show you how to output HTML:
document.writeln('<font face="Arial" size="5" color="red">Hello there!</font>');
This will display the following on the page:
Hello there!
As you can see, this allows you to just put standard HTML code into a web page using JavaScript. If you can't see a good reason for this it is not surprising at the moment but next I will introduce variables to the script.
Outputting Variables
If you look at the final example I did in the last part, where I took information from the user and added it to some other text before displaying the output in an alert box. This can also be displayed in the page. Before doing this, though, I will explain a little more about where you can put your JavaScript code.
Up until now all the JavaScrit code has been contained inside the <head> and </head> tags of the HTML document. The reason for this is that the JavaScript will be loaded and executed before the rest of the document. This works fine for most scripts but, as the scripts become more advanced, you may need to have them both in the document and the head. I will use this script to demonstrate.
To put JavaScript in the <body></body> section of the page is exactly the same as putting it in the <head></head> section of the page. I would suggest that you adopt the following way of creating scripts:
Put all your initialization code in the head of the page (like setting variables, prompts, alerts etc.) and then all display code (document.writeln etc.) in the body of the page. This is the code for the new improved version of the example which uses document.writeln:
<html>
<head>
<title>Variable Example</title>
<script>
<!-- Start Hide
// Set Variables
var welcome_text = 'Hello there ';
var closing_text = '! How are you?';
// Display prompt
var your_name = prompt('Please enter your name', 'Your name');
// Create Output Variable
var output_text = welcome_text + your_name + closing_text;
// End Hide-->
</script>
</head>
<body>
<script>
<!-- Start Hide
// Display Text
document.writeln('<font face="Arial" size="4">' + output_text + '</font><Br><Br>');
// End Hide-->
</script>
<a href="index3.htm#variables"><font face="Arial">Back</font></a>
</body>
</html>
You can see this code in action here.
As you can see from the above code, variables are added into document.writeln by using the + signs. There are no quotes round the variable names.
Remote JavaScript
Now you have learnt how to use the document.writeln command you can now start using one of the most useful applications of JavaScript, remote scripting. This allows you to write a JavaScript in a file which can then be 'called' from any other page on the web.
This can be used for things on your own site which you may like to update site-wide (like a footer on the bottom of every page) or something used on remote sites (for e
xample newsfeed or some counters).
To insert a remote JavaScript you do the following:
<script language="JavaScript" src="http://www.yourdomain.com/javascript.js">
</script>
Which will then run the JavaScript stored at http://www.yourdomain.com/javascript.js. The .js file is also very simple to make, all you have to do is write your JavaScript (omitting the <script>, </script>, <!--Start Hide and // End Hide--> tags into a simple text file and save it as something.js.
If you want to include information for browsers which do not support JavaScript you will need to put the <noscript></noscript> tags in the HTML, not the JavaScript file.
There is one problem with using remote JavaScript which is that only the recent browsers support it. Some browsers which support JavaScript do not support Remote JavaScript. This makes it advisable not to use this for navigation bars and important parts of your site.

Javascript Tutorial - Part 3

Javascript Tutorial - Part 2

 

Introduction
In part 1 I showed you how to declare a JavaScript and make sure that non-compatible browsers can see something. In this part I will show you how to actually do something with your JavaScript.
Alerts
The first JavaScript command I will show you is:
alert()
This command will make a popup box appear (click here to see it in action). This can be useful for warning users about things or (in some cases) giving them instructions. It is used in the following way:
alert('Text for alert box');
In the example above I have used single quotations ' but you could use double quotations if you want to ". They work exactly the same way. The reason I use single quotes is because, later on, when you are using HTML code and JavaScript together you will need to use them and it is good to be consistent.
Here is the full JavaScript for the earlier example:
<script>
<!-- Start Hide
// Display the alert box
alert('This text is in an alert box');
// End Hide-->
</script>
This is placed between the <head> and </head> tags of the page. As you can see, I have used a comment tag as well as the alert box code. This makes your code more readable but is not essential.
Variables
Variables in JavaScript, as in other computer languages, can be used to store information. For example I could tell the computer that the variable called:
my_number
should have the value:
3456
Variables can also contain text for example the variable:
my_name
could have the value:
David Gowans
Variables can be very useful for text or numbers that you repeat several times in a program, for doing calculations or for getting input from a user. Variables are declared as follows:
Number:
var my_number = 3456;
Strings (text):
var my_name = 'David Gowans';
As you can see a string is included in quotes (either single or double) but a number does not. If you include a number in quotes it will not be treated as a number. You may also notice that each line ends with a semicolon. This is standard JavaScript code to show the end of a line. Always remember to put it in.
When naming your strings you can use any word or combination of words as long as it is not already in use by JavaScript (so don't use alert as a variable name etc.). Do not include spaces, replace them with _.
Calculations
You can do calculations if you have variables containing numbers. Here is an example of some code which does a calculation:
// Set Variables
var first_number = 15;
var second_number = 5;
var third_number = 10;
var fourth_number = 25;
//Do Calculations
var new_number = first_number + second number
var answer = new_number * third_number
var answer = answer / fourth_number
This code sets four number variables. It then adds the first and second numbers together and stores the answer as a variable called new_answer. Then it multiplies new_number by the third number and stores the answer as answer. Finally, it divides the answer by the fourth_number to get a new value for the answer.
Getting Information From The User
Once you have started using variables you will realize that it will be quite useful to get some information from the user. You can do this by using the:
prompt()
command. Take a look at this example. I will explain how this works.
First of all, the new prompt command is used. I set the variable your_n
ame using it:
var your_name = prompt('Please enter your name', 'Your Name');
The text between the first set of quotes is what is written on the prompt box. The text between the second set of quotes is what is the default text for the input section of the box.
After this I have to create the output string. I do this by adding together the input with two strings I declared earlier (view the source on the example page for more information):
var output_text = welcome_text + your_name + closing_text;
As you can see this is much the same as adding 3 numbers together but, as these are strings they will be put one after the other (you could have also used quotes in here to add text and strings together). This added the text I had set as the welcome_text to the input I had received and then put the closing_text on the end.
Finally I displayed the output_text variable in an alert box with the following code:
alert(output_text);
which, instead of having text defined as the content for the alert box, places the string in the box.

Javascript Tutorial - Part 2

Javascript Tutorial - Part 1

 

Introduction
Thousands of sites around the world use JavaScript but it is still not a particularly well known programming language (compared to HTML). If you have seen anything interactive on a website like a calculation, pop-up-window, some web counters and even some navigation systems then you have probably seen JavaScript.
Unfortunately, JavaScript has changed from being a language which improves web sites to a language which destroys them. This is because there are huge JavaScript sites which have thousands of scripts for download. These usually involve things which do not benefit a website at all, like status bar effects and scrolling text which do not add much to a website.
JavaScript must not be confused with Java. Java is a completely different programming language. It is usually used for text effects and games, although there are some JavaScript games around.
So why should you use JavaScript? Well, JavaScript can allow you to create new things on your website that are both dynamic and interactive, allowing you to do things like find out some information about a user (like monitor resolution and browser), check that forms have been filled in correctly, rotate images, make random text, do calculations and many other things.
In this tutorial I am assuming that you understand HTML.
What Do I Need?
You will not need any special hardware or software to write JavaScript, you can just use Notepad or any other text editor. You do not even need to have any special software on your webserver. JavaScript will run on any webserver anywhere! All you will need to do is make sure that you have at least a version 3 browser, as versions of Internet Explorer and Netscape Navigator before this do not support JavaScript, so you will not be able to see your creations.
Declaring JavaScript
Adding JavaScript to a web page is actually surprisingly easy! To add a JavaScript all you need to add is the following (either between the <head></head> tags or between the <body></body> tags - I will explain more about this later):
<script language="JavaScript">
JavaScript
</script>
As you can see the JavaScript is just contained in a normal HTML tag set. The next thing you must do is make sure that the older browsers ignore it. If you don't do this the code for the JavaScript will be shown which will look awful.
There are two things you must do to hide the code from older browsers and show something instead:
<script language="JavaScript">
<!--Begin Hide
JavaScript
// End Hide-->
</script>
<noscript>
HTML Code
</noscript>
As you can see this makes the code look a lot more complex, but it is really quite simple. If you look closely you can see that all that has been done is that the JavaScript is now contained in an HTML comment tag. This is so that any old browsers which do not understand <script> will just think it is an HTML comment and ignore it.
Because of this the <noscript> tag was created. This will be ignored by browsers which understand <script> but will be read by the older browsers. All you need to do is put between <noscript> and </noscript> what you want to appear if the browser does not support JavaScript. This could be an alternative feature or just a message saying it is not available. You do not have to include the tag if you don't want anything shown instead.
Commenting
Something you might have noticed in the example above was that on the line:
// End Hide-->
There was a:
//
which does not usually appear in an HTML comment. This is because it is the sign for a JavaScript comment (it was included here to stop the browser from thinking the closing HTML tag was a piece of JavaScript).
It is very important in JavaScript, as with any other programming language t
o include comments, especially if you want others to learn from your code. It is also useful for including a copyright message.

Javascript Tutorial - Part 1

.htaccess Tutorial - Part 3

 

Introduction
Although there are many uses of the .htaccess file, by far the most popular, and probably most useful, is being able to relaibly password protect directories on websites. Although JavaScript etc. can also be used to do this, only .htaccess has total security (as someone must know the password to get into the directory, there are no 'back doors')
The .htaccess File
Adding password protection to a directory using .htaccess takes two stages. The first part is to add the appropriate lines to your .htaccess file in the directory you would like to protect. Everything below this directory will be password protected:
AuthName "Section Name"
AuthType Basic
AuthUserFile /full/path/to/.htpasswd
Require valid-user
There are a few parts of this which you will need to change for your site. You should replace "Section Name" with the name of the part of the site you are protecting e.g. "Members Area".
The /full/parth/to/.htpasswd should be changed to reflect the full server path to the .htpasswd file (more on this later). If you do not know what the full path to your webspace is, contact your system administrator for details.
The .htpasswd File
Password protecting a directory takes a little more work than any of the other .htaccess functions because you must also create a file to contain the usernames and passwords which are allowed to access the site. These should be placed in a file which (by default) should be called .htpasswd. Like the .htaccess file, this is a file with no name and an 8 letter extension. This can be placed anywhere within you website (as the passwords are encrypted) but it is advisable to store it outside the web root so that it is impossible to access it from the web.
Entering Usernames And Passwords
Once you have created your .htpasswd file (you can do this in a standard text editor) you must enter the usernames and passwords to access the site. They should be entered as follows:
username:password
where the password is the encrypted format of the password. To encrypt the password you will either need to use one of the premade scripts available on the web or write your own. There is a good username/password service at the KxS site which will allow you to enter the user name and password and will output it in the correct format.
For multiple users, just add extra lines to your .htpasswd file in the same format as the first. There are even scripts available for free which will manage the .htpasswd file and will allow automatic adding/removing of users etc.
Accessing The Site
When you try to access a site which has been protected by .htaccess your browser will pop up a standard username/password dialog box. If you don't like this, there are certain scripts available which allow you to embed a username/password box in a website to do the authentication. You can also send the username and password (unencrypted) in the URL as follows:
http://username:password@www.website.com/directory/
Summary
.htaccess is one of the most useful files a webmaster can use. There are a wide variety of different uses for it which can save time and increase security on your website.

.htaccess Tutorial - Part 3

.htaccess Tutorial - Part 2

 

Introduction
In the last part I introduced you to .htaccess and some of its useful features. In this part I will show you how to use the .htaccess file to implement some of these.
Stop A Directory Index From Being Shown
Sometimes, for one reason or another, you will have no index file in your directory. This will, of course, mean that if someone types the directory name into their browser, a full listing of all the files in that directory will be shown. This could be a security risk for your site.
To prevent against this (without creating lots of new 'index' files, you can enter a command into your .htaccess file to stop the directory list from being shown:
Options -Indexes
Deny/Allow Certian IP Addresses
In some situations, you may want to only allow people with specific IP addresses to access your site (for example, only allowing people using a particular ISP to get into a certian directory) or you may want to ban certian IP addresses (for example, keeping disruptive memembers out of your message boards). Of course, this will only work if you know the IP addresses you want to ban and, as most people on the internet now have a dynamic IP address, so this is not always the best way to limit usage.
You can block an IP address by using:
deny from 000.000.000.000
where 000.000.000.000 is the IP address. If you only specify 1 or 2 of the groups of numbers, you will block a whole range.
You can allow an IP address by using:
allow from 000.000.000.000
where 000.000.000.000 is the IP address. If you only specify 1 or 2 of the groups of numbers, you will allow a whole range.
If you want to deny everyone from accessing a directory, you can use:
deny from all
but this will still allow scripts to use the files in the directory.
Alternative Index Files
You may not always want to use index.htm or index.html as your index file for a directory, for example if you are using PHP files in your site, you may want index.php to be the index file for a directory. You are not limited to 'index' files though. Using .htaccess you can set foofoo.blah to be your index file if you want to!
Alternate index files are entered in a list. The server will work from left to right, checking to see if each file exists, if none of them exisit it will display a directory listing (unless, of course, you have turned this off).
DirectoryIndex index.php index.php3 messagebrd.pl index.html index.htm
Redirection
One of the most useful functions of the .htaccess file is to redirect requests to different files, either on the same server, or on a completely different web site. It can be extremely useful if you change the name of one of your files but allow users to still find it. Another use (which I find very useful) is to redirect to a longer URL, for example in my newsletters I can use a very short URL for my affiliate links. The following can be done to redirect a specific file:
Redirect /location/from/root/file.ext http://www.othersite.com/new/file/location.xyz
In this above example, a file in the root directory called oldfile.html would be entered as:
/oldfile.html
and a file in the old subdirectory would be entered as:
/old/oldfile.html
You can also redirect whole directoires of your site using the .htaccess file, for example if you had a directory called olddirectory on your site and you had set up the same files on a new site at: http://www.newsite.com/newdirectory/ you could redirect all the files in that directory without having to specify each one:
Redirect /olddirectory http://www.newsite.com/newdirectory
Then, any request to your site below /olddirectory will bee redirected to the new site, with the
extra information in the URL added on, for example if someone typed in:
http://www.youroldsite.com/olddirecotry/oldfiles/images/image.gif
They would be redirected to:
http://www.newsite.com/newdirectory/oldfiles/images/image.gif
This can prove to be extremely powerful if used correctly.

.htaccess Tutorial - Part 2

.htaccess Tutorial - Part 1

 

Introduction
In this tutorial you will find out about the .htaccess file and the power it has to improve your website. Although .htaccess is only a file, it can change settings on the servers and allow you to do many different things, the most popular being able to have your own custom 404 error pages. .htaccess isn't difficult to use and is really just made up of a few simple instructions in a text file.
Will My Host Support It?
This is probably the hardest question to give a simple answer to. Many hosts support .htaccess but don't actually publicise it and many other hosts have the capability but do not allow their users to have a .htaccess file. As a general rule, if your server runs Unix or Linux, or any version of the Apache web server it will support .htaccess, although your host may not allow you to use it.
A good sign of whether your host allows .htaccess files is if they support password protection of folders. To do this they will need to offer .htaccess (although in a few cases they will offer password protection but not let you use .htaccess). The best thing to do if you are unsure is to either upload your own .htaccess file and see if it works or e-mail your web host and ask them.
What Can I Do?
You may be wondering what .htaccess can do, or you may have read about some of its uses but don't realise how many things you can actually do with it.
There is a huge range of things .htaccess can do including: password protecting folders, redirecting users automatically, custom error pages, changing your file extensions, banning users with certian IP addresses, only allowing users with certain IP addresses, stopping directory listings and using a different file as the index file.
Creating A .htaccess File
Creating a .htaccess file may cause you a few problems. Writing the file is easy, you just need enter the appropriate code into a text editor (like notepad). You may run into problems with saving the file. Because .htaccess is a strange file name (the file actually has no name but a 8 letter file extension) it may not be accepted on certain systems (e.g. Windows 3.1). With most operating systems, though, all you need to do is to save the file by entering the name as:
".htaccess"
(including the quotes). If this doesn't work, you will need to name it something else (e.g. htaccess.txt) and then upload it to the server. Once you have uploaded the file you can then rename it using an FTP program.
Warning
Before beginning using .htaccess, I should give you one warning. Although using .htaccess on your server is extremely unlikely to cause you any problems (if something is wrong it simply won't work), you should be wary if you are using the Microsoft FrontPage Extensions. The FrontPage extensions use the .htaccess file so you should not really edit it to add your own information. If you do want to (this is not recommended, but possible) you should download the .htaccess file from your server first (if it exists) and then add your code to the beginning.
Custom Error Pages
The first use of the .htaccess file which I will cover is custom error pages. These will allow you to have your own, personal error pages (for example when a file is not found) instead of using your host's error pages or having no page. This will make your site seem much more professional in the unlikely event of an error. It will also allow you to create scripts to notify you if there is an error (for example I use a PHP script on Free Webmaster Help to automatically e-mail me when a page is not found).
You can use custom error pages for any error as long as you know its number (like 404 for page not found) by adding the following to your .htaccess file:
ErrorDocument errornumber /file.html
For example if I had the file notfound.html in the root direct
ory of my site and I wanted to use it for a 404 error I would use:
ErrorDocument 404 /notfound.html
If the file is not in the root directory of your site, you just need to put the path to it:
ErrorDocument 500 /errorpages/500.html
These are some of the most common errors:
401 - Authorization Required
400 - Bad request
403 - Forbidden
500 - Internal Server Error
404 - Wrong page
Then, all you need to do is to create a file to display when the error happens and upload it and the .htaccess file

.htaccess Tutorial - Part 1

Saturday, July 7, 2007

PHP Tutorial - Part 6

 

Introduction
In the last part, I showed you how to use PHP to send e-mail messages using a script. In this part I will continue this and also show you how to use PHP and forms together to make your PHP scripts useful.
Setting Up Your Form
Setting up a form for use with a PHP script is exactly the same as normal in HTML. As this is a PHP tutorial I will not go into depth in 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 Your Name written in it as default. The value section of this code is optional. The information defined by 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.
All the elements for your form must be enclosed in the <form> tags. They are used as follows:
<form action="process.php" method="post">
Form elements and formatting etc.
</form>
The form's action tells it what script to send its data to (in this case its process.php). This can also be a full URL (e.g. http://www.mysite.com/scripts/private/processors/process.php). The method tells the form how to submit its data. POST will send the data in a data stream to the script when it is requested. GET is the other option. GET will send the form data in the form of the url so it would appear after a question mark e.g. http://www.mysite.com/process.php?name=david
It really makes no difference which system you use but it is normally better to use POST if you are using passwords or sensitive information as they should not be shown in the browser's address bar.
Getting The Form Information
The next step is to get the data the form has submitted into your script so that you can do something with it. This is. There are basically two different methods of getting the data into PHP, which depend on how they were submitted. There are two submission methods, GET and POST, which can both be used by forms. The difference between the two is that using GET, the variables and data will be shown in the page address, but using POST it is invisible. The benefit of GET, though is that you can submit information to the script without a form, by simply editing the URL.
This works the same as submitting a form using GET. The advantage of this is that you can create links to your scripts which do different things depending on the link clicked. For example you could create a script which will show different pages depending on the link clicked:
yourpage.php?user=david
could show David's page and:
yourpage.php?user=tom
could show Tom's page, using the same script.
It is also possible to pass more than one piece of information to the script using this system by separating them with the & symbol:
yourpage.php?user=david&referrer=gowansnet&area=6
These could all be accessed separately using the GET variables user, referrer and area.
To get a variable which has been sent to a script using the POST method you use the following code:
$variablename=$_POST['variable'];
which basically takes the variable from the POST (the name of a form field) and assigns it to the variable $variablename.
Similarly, if you are using the GET method you should use the form:
$variablename=$_GET['variable'];
This should be done for each variable you wish to use from your form (or URL).
Creating The Form To Mail Script
To finish off this section, I will show you how to use what you have learnt in this part and the last to create a system which will e-mail a user's comments to you.
Firstly, create this form for your HTML page:
<form action="mail.php" method="post">
Your Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br><br>
Comments<br>
<textarea name="comments"></textarea><br><br>
<input type="submit" value="Submit">
</form>
This will make a simple form where the user can enter their e-mail address, their name and their comments. You can, of course, add extra parts to this form but remember to update the script too. Now create the PHP script:
<?
function checkOK($field)
{
if (eregi("\r",$field) || eregi("\n",$field)){
die("Invalid Input!");
}
}
$name=$_POST['name'];
checkOK($name);
$email=$_POST['email'];
checkOK($email);
$comments=$_POST['comments'];
checkOK($comments);
$to="php@gowansnet.com";
$message="$name just filled in your comments form. They said:\n$comments\n\nTheir e-mail address was: $email";
if(mail($to,"Comments From Your Site",$message,"From: $email\n")) {
echo "Thanks for your comments.";
} else {
echo "There was a problem sending the mail. Please check that you filled in the form correctly.";
}
?>
Remember to replace php@gowansnet.com with your own e-mail address. This script should be saved as mail.php and both should be uploaded. Now, all you need to do is to fill in your comments form.
The first part of that script may look a bit strange:
function checkOK($field)
{
if (eregi("\r",$field) || eregi("\n",$field)){
die("Invalid Input!");
}
}
You don't really need to worry about what this is doing, but basically, it stops spammers from using your form to send thier spam messages by checking special characters are not present in the input which can be used to trick the computer into sending messages to other addresses. It is a fuction which checks for these characters, and if they are found, stops running the script.
The lines:
checkOK($name);
etc. run this check on each input to ensure it is valid.

PHP Tutorial - Part 6

PHP Tutorial - Part 5

 

Introduction
One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.
The Mail Command
Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:
mail($to,$subject,$body,$headers);
In this example I have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail.
The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mai but you can also include other headers like cc and bcc.
Sending An E-mail
Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:
$to = "php@gowansnet.com";
$subject = "PHP Is Great";
$body = "PHP is one of the best scripting languages around";
$headers = "From: webmaster@gowansnet.com\n";
mail($to,$subject,$body,$headers);
echo "Mail sent to $to";
This code will acutally do two things. Firstly it will send a message to php@gowansnet.com with the subject 'PHP Is Great' and the text:
PHP is one of the best scripting languages around
and the e-mail will be from webmaster@gowansnet.com. It will also output the text:
Mail sent to php@gowansnet.com
to the browser.
Formatting E-mail
Something you may have noticed from the example is that the From line ended with \n. This is acutally a very important character when sending 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 and will be delivered.
The \n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.
Mail Without Variables
The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:
mail("php@gowansnet.com","PHP Is Great","PHP is one of the best scripting languages around","From: webmaster@gowansnet.com\n");
But that would make your code slightly harder to read.
Error Control
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 (especially if you are using your script for form to mail). Because of this, you can add in a small piece of code which will check if the e-mail is 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. Check your code and make sure that the e-mail address $to is valid";
}
This code is quite self explanitory. If the mail is sent successfully it will output a message to the browser telling the user, if not, it will display an error message with some suggestions for correcting the problem.

PHP Tutorial - Part 5

PHP Tutorial - Part 4

 

Introduction
In the last parts of this tutorial I have showed you how to deal with text and variables in PHP and how you can use IF statements to compare them and to make decisions. In this part I am going to show you how to use another important part of PHP, loops.
The WHILE Loop
The WHILE loop is one of the most useful commands 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.
Repeating A Set Number Of Times
If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop. For instance if you wanted to print out the words "Hello World" 5 times you could use the following code:
$times = 5;
$x = 0;
while ($x < $times) {
echo "Hello World";
++$x;
}
I will now explain this code. The first two lines are just setting the variables. The $times variable holds the number of times you want to repeat the code. The $x variable is the one which will count the number of times the code has been executed. After these is the WHILE line. This tells the computer to repeat the code while $i is less than $times (or to repeat it until $i is equal to $times). This is followed by the code to be executed which is enclosed in { }.
After the echo line which prints out the text, there is another very important line:
++$x;
What this does is exactly the same as writing:
$x = $x + 1;
It adds one to the value of $x. This code is then repeated (as $x now equals 1). It continues being repeated until $x equals 5 (the value of times) when the computer will then move on to the next part of the code.
Using $x
The variable counting the number of repeats ($x in the above example) can be used for much more than just counting. For example if you wanted to create a web page with all the numbers from 1 to 1000 on it, you could either type out every single one or you could use the following code:
$number = 1000;
$current = 0;
while ($current < $number) {
++$current;
echo "$current<br>";
}
There are a few things to notice about this code. Firstly, you will notice that I have placed the ++$current; before the echo statement. This is because, if I didn't do this it would start printing numbers from 0, which is not what we want. The ++$current; line can be placed anywhere in your WHILE loop, it does not matter. It can, of course, add, subtract, multiply, divide or do anthing else to the number as well.
The other reason for this is that, if the ++$current; line was after the echo line, the loop would also stop when the number showed 999 because it would check $current which would equal 1000 (set in the last loop) and would stop, even though 1000 had not yet been printed.
Arrays
Arrays are common to many programing 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 WHILE loops.
Setting Up An Array
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 in 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 a number in [ ].
Reading From An Array
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 number of the piece of data in the array. So if I wanted to print out the third name I could use the code:
n
echo "The third name is $names[2]";
Which would output:
The third name is Steven
Using Arrays And Loops
One of the best uses of a loop is to output the information in an array. For instance if I wanted 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.

PHP Tutorial - Part 4

PHP Tutorial - Part 3

 

Introduction
Over the past two parts I have shown you the basics of text in PHP and how to store it as variables. In this part of the tutorial I will show you how to use IF statements to make decisions in your scripts.
The Basics Of IF
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, 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 Strucure
The structure of an IF statement is as follows:
IF (something == something else)
{
THEN Statement
} else {
ELSE Statement
}
Variables
The most common use of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example:
if ($username == "webmaster")
which 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 of the quotation marks so if the variable contained 'Webmaster' or 'WEBMASTER' it will be false.
Constructing The THEN Statment
To add to your script, you 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.
Constructing The ELSE Statement
Adding The ELSE statement is as easy as 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 other IF statments (nested statements).
Other Comparisons
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 comparision 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";
}

PHP Tutorial - Part 3

PHP Tutorial - Part 2

 

Introduction
In the last part of the tutorial I explained some of the advantages of PHP as a scripting language and showed you how to test your server for PHP. In this part I will show you the basics of showing information in the browser and how you can use variables to hold information.
Printing Text
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 print. Print will allow you to output text, variables or a combination of the two so that they display on the screen.
The print statement is used in the following way:
print("Hello world!");
I will explain the above line:
print is the command and tells the script what to do. This is followed by the information to be printed, which is contained in the brackets. Because you are outputting text, the text is also enclosed instide quotation marks. Finally, as with nearly every line in a PHP script, it must end in a semicolon. You would, of course, have to enclose this in your standard PHP tags, making the following code:
<?
print("Hello world!");
?>
Which will display:
Hello world!
on the screen.
Variables
As with other programming languages, PHP allows you to define variables. In PHP there are several variable types, but the most common is called a String. It can hold text and numbers. All strings begin with a $ sign. To assign some text to a string 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 string. You must remember a few rules about strings though:
Strings are case sensetive so $Welcome_Text is not the same as $welcome_text
String names can contain letters, numbers and underscores but cannot begin with a number or underscore
When assigning numbers to strings you do not need to include the quotes so:
$user_id = 987
would be allowed.
Outputting Variables
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.";
print($welcome_text);
?>
As you can see, the only major difference is that you do not need the quotation marks if you are printing a variable.
Formatting Your Text
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. 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 means that you must 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 Arial font in red. The normal code for this would be:
<font face="Arial" color="#FF0000">
</font>
As you can see this code contains 4 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 chang
e to:
<font face=\"Arial\" color=\"#FF0000\">
</font>
You can now include this in your print statement:
print("<font face=\"Arial\" color\"#FF0000\">Hello and welcome to my website.</font>");
which will make the browser display:
Hello and welcome to my website.
because it has only been sent the code:
<font face="Arial" color="#FF0000">Hello and welcome to my website.</font>
This does make it quite difficult to output HTML code into the browser but later in this tutorial I will show you another way of doing this which can make it a bit easier.

PHP Tutorial - Part 2

PHP Tutorial - Part 1

 

Introduction
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 becomming easier to learn and PHP is one of the easiest and most powerful yet.
What Is PHP?
PHP stands for Hypertext Preprocessor and is a server-side 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 relatively new (compared to languages such as Perl (CGI) and Java) but is quickly becomming one of the most popular scripting languages on the internet.
Why PHP?
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 Hotscripts, 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, counters and even more advanced features like portal systems, content management, advertising managers 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 scripting language.
What Do I Need?
As mentioned earlier, PHP is a server-side scripting language. This means that, although your users will not need to install new software, you 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 in this tutorial. If you 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 recommmend HostRocket.
Writing PHP
Writing PHP on your computer is actually very simple. You don't need any specail software, except for a text editor (like Notepad in Windows). Run this and you are ready to write your first PHP script.
Declaring PHP
PHP scripts are always enclosed in between two PHP tags. This tells your server to parse the information between them as PHP. The three different forms are as follows:
<?
PHP Code In Here
?>
<?php
PHP Code In Here
php?>
<script language="php">
PHP Code In Here
</script>
All of these work in exactly the same way but in this tutorial I will be using the first option (<? and ?>). There is no particular reason for this, though, and you can use either of the options. You must remember, though, to start and end your code with the same tag (you can't start with <? and end with </script> for example).
Your First Script
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:
<?
phpinfo();
?>
As you can see this 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 th
at 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.
Finishing and Testing Your Script
Now you have finished your script save it as phpinfo.php and upload it to your server in the normal way. Now, using your browser, go the the URL of the 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 serach for a new web host or ask your current host to install PHP.
It is a good idea to keep this script for future reference.

PHP Tutorial - Part 1

CSS Tutorial IV

 

In part 2 of the tutorial we broke down the major sections of HTML on the page and established separation using DIV tags with unique ID's attached to them:

<div id="navigation"> ... </div>

<div id="centerDoc"> ... </div>

Using DIV's (to position the major page sections) is the alternate method to what most people use: tables. I would argue one method is not necessarily better than the other. But consider that CSS in the 'official' method to position page elements and tables should only be used to hold tabular data.

On the other hand there are simply times when using tables is much easier and CSS just doesn't cut it. With our current layout (left or right side navigation) CSS is far easier to use and is an overall better solution.

Now that we have that covered, everything gets really easy from here. We've established our main document and the major sections are in place, all we need to do is add our text and images.

Breaking down the page:

This page is simple, we have just a single heading:

<h1>The Main Heading</h1>

And a single paragraph:

<p>

Go to the Web Designers Killer Handbook home page and grab the practice HTML page that we will used as the starting template for this tutorial. You can find it under the heading: 'To create the practice HTML page do the following:'. Follow the instructions there and create your basic HTML page ... and do it now!

</p>

We define how the paragraphs and the headings will look in our CSS code:

p {

width: 80%;

}

h1 {

font-family: Georgia, "Times New Roman", Times, serif;

font-size: 18px;

font-weight: bold;

color: #000000;

}

This is pretty much self-explanatory. The only thing that should be mentioned is that we set the width of the <p> tags to 80%. This allows us to control all of our text width in one easy to edit spot.

The only thing missing from the page is the actual navigation. The best and easiest way to do this, is by using list (<li>) tags. That makes sense, since navigational menus are essentially a list of pages.

We styled the list item tags with this CSS:

li {

list-style-type: none;

line-height: 150%;

list-style-image: url(../images/arrowSmall.gif);

}

The above code uses an image as the bullets for the list and makes the space between the listed items 1 and ½ times larger than normal (I like a little more 'breathing room'). You don't have to have an image for the bullets, you could leave it with no images and no bullets by just removing the attribute:

list-style-image: url(../images/arrowSmall.gif);

Or you could use on of the built in bullet options: 'disc', 'circle' and 'square'.

Next you should add to the HTML page an unordered list (<ul></ul>) in between the navigation DIV's just under the 'main navigation' heading:

<h2>The Main navigation</h2>

<ul>

<li><a href="cssTutorialPage1.htm">Page One</a></li>

<li><a href="cssTutorialPage2.htm">Page Two</a></li>

</ul>

To make things easier (for the purpose of the article), change the CSS affecting the list item tags (<li>) so that we use a built in bullet:

li {

list-style-type: disc;

line-height: 150%;

}

Now we have the navigation!

That pretty much covers our goals for this tutorial, but we have just scratched the surface of CSS. As you can see, we created a nice looking page, while using very few types of HTML tags. At this time there isn't much text on the page, but we could add to the page easily, building it out to include lots of information and images with practically no HTML work at all!

I hope the CSS tutorial was useful for you all, it may have been a little hard to get your head wrapped around this subject at first, but in time you will see that your efforts will pay off. Please let me know how you felt about this article.

Thanks for reading and don’t be afraid to write me should you have questions!

Stefan Mischook

CSS Tutorial

CSS Tutorial III

 

In Part 1 we created a classic two-column layout with left side navigation using CSS and only a few types of HTML tags.

Part 1 presented the code for the page and explained what HTML tags we were going to use. Now we will look at the actual HTML code used so far and the CSS.

Our page so far is really very simple. As you may already know, all the content (text, images, Flash etc) that the user sees when viewing a web page is marked-up/coded with HTML in-between the <body> and </body> tags*.

In this case we have this:

<body>

<div id="navigation">

<h2>The Main navigation</h2>

</div>

<div id="centerDoc">

<h1>The Main Heading</h1>

<p>

Go to the Web Designers Killer Handbook home page and grab the practice HTML page that we will used as the starting template for this tutorial. You can find it under the heading: 'To create the practice HTML page do the following:'.

Follow the instructions there and create your basic HTML page ... and do it now!

</p>

</div>

</body>

In the above code we see that we have 2 main sections demarked by using <div> tags. As you learned in part one of this tutorial, <div> tags are designed to be used to create a 'division' in the document or in other words create a container. We have created two such containers and given them each of them a unique ID:

<div id="navigation">

...

<div id="centerDoc">

You will notice that the entire contents of the page are contained in one of these two major page divisions. So the first questions are what are the rules of ID's in HTML pages and why do we use them and assign them to page elements like DIVs?

1. First of all you can assign ID's to any HTML tag. So I could have assigned an ID to a <p> tag as well.

2. An ID in a page should only be used once. That is to say that no two elements should have the same ID. ID's are meant to uniquely identify a page element. So in the above example we know that there is only one page element with an ID of 'navigation' and only page element with an ID of 'centerDoc'. I like to use ID names that talk to you, it is pretty clear what is going on in each division we created above.

3. ID's on HTML page elements (tags) are used in CSS. We can target ID's in our CSS code to change the appearance, position and even behavior of that element by referencing the ID of the element.

Inside the <div> tags we use header tags (<h1> and <h2>) to set the headers. I speak to what header tags mean in part 1 of this tutorial.

And finally I have some <p> tags, and of course I insert the text that makes up this simple page in-between them.

Now I am going to jump to our CSS file that is attached to the HTML page. We attach the CSS document with this line of code in between the <head> </head> tags:

<head>

<link href="myCSS.css" rel="stylesheet" type="text/css">

</head>

Like a normal page link we have an 'href' attribute this time pointing to a CSS document that has all our CSS code that will affect this page since it is linked to it. This is not the only way to associate CSS code to pages (there are a few other ways) but we will leave that to another article. So in the above link we name the CSS file name with this: 'href="myCSS.css"' and we tell the browser that the link is to a CSS page with this attribute: 'type="text/css"'. All that is important here is that the link point to a CSS file with the name: 'myCSS.css'

So now that we got the style sheet linked to the document, lets look at some CSS code. This first snippet of code 'styles' the unique ID's we were talking about before:

#navigation {

position: absolute;

width: 210px;

height: 600px;

margin: 0;

margin-top: 0px;

border-right: 1px solid #C6EC8C;

font-weight: normal;

}

#centerDoc {

position: absolute;

padding: 0 0 20px 0; /*top right bottom left*/

margin-top: 50px;

margin-left: 235px;

}

There is a lot going on here so we will focus on just a few elements for now. In the above elements we have 2 selectors, one for each ID and each selectors are grouped/contained by using the curly brackets: { }. So here is the CSS selectors code with all their guts removed:

#navigation {

/*Look ma no CSS rules!*/

}

#centerDoc {

/*Look ma no CSS rules!*/

}

I just inserted the text: '/*Look ma no CSS rules!*/' to show you where the CSS code would normally be. So now you can see that anything in between the curly brackets is part of one group or package that in CSS can generically be called a selector.

In our above examples you can see that there is some text that appears before a curly bracket. That text gives a name to the selector. So in this case we have two selector names and thus to selectors: #centerDoc and #navigation. So why do we have the # symbol in front of the text? Why can't we call it simply 'centerDoc' and 'navigation'?

Like HTML and programming certain text in certain places have special meaning that tells the system to do something particular. In this case whenever you have a # symbol in front of a name of a CSS selector we are saying that this selector is a special type of selector called an 'ID' selector. What is so special about an ID selector? That type of selector can only be applied to one element in the HTML page. Sounds familiar?

So those of you not asleep at the computer, now see that we have a CSS ID selector for each of our HTML divs that have an ID, and they have the same corresponding names. So the CSS selector #centerDoc applies to the div: '<div id="centerDoc">' , you got it? Whatever CSS rules/styles we choose to code into our ID selector will change what appears inside the corresponding div. So for the div with the id of: 'navigation' we have these CSS rules:

#navigation {

position: absolute;

width: 210px;

height: 600px;

margin: 0;

margin-top: 0px;

border-right: 1px solid #C6EC8C;

font-weight: normal;

}

Notice at the bottom we say all text will have a font-weight of 'normal':

font-weight: normal;

We could just as easily have said that we want all the text to appear in the div (the div with the ID 'navigation') bold instead:

font-weight: bold;

But I digress, I already go into detail about CSS in a my previous article on CSS. This tutorial was about creating an easy to use page template so I will point out the 2 main elements that make this thing work.

In our page the navigation div is sitting on the left and it has a border ... why? It has a nice light green 1 pixel border because I set this in my CSS:

border-right: 1px solid #C6EC8C;

Pretty self explanatory, no? I would suggest changing the color of the border and changing the pixel thickness of the border and see how it looks.

Why is the navigation sitting on the left of the page while the centerDoc is to the right of it? Well first thing to look at is this line in the navigation selector:

position: absolute;

This tells the browser to just place this div on the page as is. This is oversimplifying the subject, but for our purposes this works for now.

The real magic in this is the CSS code for centerDoc:

#centerDoc {

position: absolute;

padding: 0 0 20px 0; /*top right bottom left*/

margin-top: 50px;

margin-left: 235x;

}

The line :

padding: 0 0 20px 0; /*top right bottom left*/

Tells the browser to insert 20px (pixels) of padding to the bottom of the div with the ID 'centerDoc'.

Let's back up here a second. We just used something called 'padding' and it is what it sounds like: Space that is wrapped around our element (tag).

CSS has this feature and concept of a box model that essentially is a box that wraps around HTML elements. This box model consists of: padding, margins, borders and the actual content. This allows us to place a border around elements and space elements in relation to other elements. From the inside out it is ordered like so:

content -> padding -> border -> margin

So in our case anything in between our <div> tags is the 'content'. Right after that comes the padding. Then there is a border and finally a margin. Margin and padding may seem like the same thing but if you think about it, you can see how being able to control the space before the border (padding) and after the border (margins) can really effect your layouts.

In this example you notice that the navigation div sits higher up on the page than the centerDoc div. This is not because of the order that which they appear in the HTML, as they normally would without CSS, rather it is because of the margin settings I set for each selector; for centerDoc I set the top margin to 50px:

margin-top: 50px;

And for the navigation div I set it to:

margin-top: 0px;

This sets it's top margin to 0 pixels so it will therefore be 50 pixels higher than the centerDoc div. I would suggest that you move the position of the navigation div under the center doc div in the HTML just to see if it changes anything, you will see that where the div appears in the actual HTML code has nothing to do with how it will appear to the user now that CSS positioning has been used. Another thing to try is to play with the CSS values and see what happens, change the padding, change the margins etc .

CSS Tutorial

CSS Tutorial II

 

In this CSS tutorial I will not be able to show you everything there is about CSS, but you will learn how to create nice looking CSS styled web pages.

After completing this tutorial, you should have enough information to explore CSS and web design even further.

  • You can download the CSS and HTML files we build in this tutorial: CSS files
  • You can check out what the page should look like here: CSS example page

CSS REDUCES THE NUMBER OF TAGS USED

Because of the power of CSS, we will be able to reduce the number of HTML tags we use in a page big time, all the while still being able to layout great looking pages using only 6 types (for lack of better words) of HTML tags.

The tags we will use to layout the content:

1. <h> The Heading tags which range from '<h1></h1>' to '<h6></h6>', are going to be used to mark/tag headings in our pages. So the most important heading will be wrapped in a <h1> tag and the least important in a <h6> tag.

An example of a heading:

<h1> CSS Template Layout </h1>

This tells the browsers and the search engines too, that this page is primarily about: 'CSS Template Layout'

All browsers have a default size (for each <h> tag) as to how it renders text when placed between these tags. Many of these defaults can be unusable (especially <h1>) because they come out too big. But never fear, CSS is here. We will use CSS to make the text sizes more to our liking.

2. <p> The Paragraph tag is used to mark parts of the pages as being 'paragraphs', simple enough. Paragraph tags are what they call a 'block element'; that means that it acts like a block where a space is automatically inserted before and after each <p> tag pair. You see it work in the examples coming up.

3. <ul> and <ol> List tags will used to create our menus. The tag <ul> is the 'un-ordered list tag' that creates a list with bullets or other images/icons that do not specify or denote an order; hence the term 'un-ordered'. The other list tag mentioned (<ol>) is the 'ordered list tag' and it creates a list that, instead of bullets, the list elements are marked with numbers or letters. Code examples to follow.

4. <div> We all know what the <div> tag is about since we all read the previous article, right? We will use div's to create containers for parts of our page. One div will be used to 'hold' our navigational menu and another div to 'hold' the main page.

5. <a href> The most important tag in HTML: the 'link tag' or the 'hyperlink tag'. This makes text 'hyper' so that when we click on it we can load another page or activate/call some JavaScript (otherwise known as ECMA script).

6. <img> This is the 'image tag', allows you to link to images so that they show up in our pages. In HTML images are not embedded into the actual page, instead the image tag (<img>) only points to where the image is and the browser will attempt to load that image when a surfer loads your HTML page.

That covers the HTML tags we will use in our layout! No need for table tags, <br> tags and nasty <font> tags.

THE BASIC PAGE TEMPLATE

Go to the Web Designers Killer Handbook home page and grab the practice HTML page that we will use as the starting template for this tutorial. You can find it under the heading: 'To create the practice HTML page do the following:' Follow the instructions there and create your basic HTML page.

Once you have created the template page, create a folder and name it something like: 'myCSSwebsite' and then drop the HTML page into it. In that same folder, create a new text document and call it: 'myCSS.css'. Once created open that file and paste in this template CSS code and then save it:

/* Generic Selectors */

body {

font-family: Georgia, "Times New Roman", Times, serif;

font-size: 14px;

color: #333333;

background-color: #F9F9F9;

}

p {

width: 80%;

}

li {

list-style-type: none;

line-height: 150%;

list-style-image: url(../images/arrowSmall.gif);

}

h1 {

font-family: Georgia, "Times New Roman", Times, serif;

font-size: 18px;

font-weight: bold;

color: #000000;

}

h2 {

font-family: Georgia, "Times New Roman", Times, serif;

font-size: 16px;

font-weight: bold;

color: #000000;

border-bottom: 1px solid #C6EC8C;

}

/**************** Pseudo classes ****************/

a:link {

color: #00CC00;

text-decoration: underline;

font-weight: bold;

}

li :link {

color: #00CC00;

text-decoration: none;

font-weight: bold;

}

a:visited {

color: #00CC00;

text-decoration: underline;

font-weight: bold;

}

li a:visited {

color: #00CC00;

text-decoration: none;

font-weight: bold;

}

a:hover {

color: rgb(0, 96, 255);

padding-bottom: 5px;

font-weight: bold;

text-decoration: underline;

}

li a:hover {

display: block;

color: rgb(0, 96, 255);

padding-bottom: 5px;

font-weight: bold;

border-bottom-width: 1px;

border-bottom-style: solid;

border-bottom-color: #C6EC8C;

}

a:active {

color: rgb(255, 0, 102);

font-weight: bold;

}

/************************* ID's *************************/

#navigation {

position: absolute;

width: 210px;

height: 600px;

margin: 0;

margin-top: 50px;

border-right: 1px solid #C6EC8C;

font-weight: normal;

}

#centerDoc {

position: absolute;

padding: 0 0 20px 0; /*top right bottom left*/

margin-top: 50px;

margin-left: 235px;

}

Don't let the CSS freak you out, I will explain the important details and you will soon see how easy it really is. One last thing for you to do before I finish this part of the tutorial, we need to add some code to our HTML page.

In between the <body></body> tags you will need to insert this code:

<div id="navigation">

<h2>The Main navigation</h2>

</div>

<div id="centerDoc">

<h1>The Main Heading</h1>

<p>

Go to the Web Designers Killer Handbook home page and grab the practice HTML page that we will used as the starting template for this tutorial. You can find it under the heading: 'To create the practice HTML page do the following:'.

Follow the instructions there and create your basic HTML page ... and do it now!

</p>

</div>

And in between the <head> </head> tags you will need to insert this:

<title>First CSS Tutorial</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<link href="myCSS.css" rel="stylesheet" type="text/css">

With this in place we will be able to start styling our page. If you take a look at the HTML page now you may be surprised to see that we already started!

CSS Tutorial