Implementing Login/Logout with PHP

February 10th, 2009

Many times when you’re designing a site, you need to password protect certain parts of the site- for example the admin part of the site.

This can be quite easy to do with PHP, by using Cookies.

Start by setting up a file to contain the password etc:

settings.php:


<?php
	$admin='Admin1';
	$adminpassword='password';
?>

Then create a login file. This file will use a form and cookies to get the username/password from the visitor:

login.php:


<?php
include "settings.php";

$username = $_COOKIE['admin'];
$password = $_COOKIE['password'];

if(isset($_POST[submit]))
{
	//check if password is correct, if it is, set the cookie and go to index.php

	if($admin == $_POST[login] && $adminpassword==$_POST[password])
	{
		setcookie("admin", "$_POST[login]", time()+3600);
		setcookie("password", "$_POST[password]", time()+3600);
		header("Refresh:0; url=index.php");
		exit;
	}
}

//No admin/password, or the details are wrong... Try again...
?>

<form method = 'post' action='login.php'>
<h2>Welcome back admin</h2>

<?php
if(isset($_POST[submit]))
{
	if ($admin != $_POST[login])
	{
		echo "<b>Invalid login name<br>";
	}
	elseif ($adminpassword != $_POST[password])
	{
		echo "<b>Invalid password<br>";
	}
}
?>

<table border='0' cellpadding='5' cellspacing='0' style='border-collapse: collapse' bordercolor='#111111' width='70%' id='AutoNumber1'>
  <tr>
    <td width='20%'>Login Name</td>
    <td width='80%'><input type ='text' name='login' size='32'></td>
  </tr>
  <tr>
    <td width='20%'>Password</td>
    <td width='80%'><input type='password' name='password' size='32'></td>
  </tr>
  <tr>
  <td colspan='2' align='center'>
<input type='submit' name='submit' value='Login'> <br>
</p>
</td>
</tr>
</table>
</form>

The logout equivalent is quite easy, just blank out the cookies:

logout.php:


<?php
	setcookie("admin", "", time()-1800);
	setcookie("password", "", time()-1800);
	header("Refresh:0; url=login.php");
?>

Finally, make a checklogin page, that sees if the cookies are correct, and if they are not, redirects to the login file:

checklogin.php:


<?php
require "settings.php";
$username = $_COOKIE['admin'];
$password = $_COOKIE['password'];

//Wrong login or password
if ($admin != $username || $adminpassword != $password)
{
    header("Refresh:0; url=login.php");
	exit;
}
?>

Now, any file you want to add security for, just include “checklogin.php”

For example, if you have a.php:

a.php:

Secret Data

And you wish to password protect it, just change it to this:

<?php

require "checklogin.php"

?>

Secret Data

Thats it! checklogin.php will see if the password is set correctly. If it isn’t it uses the header command to redirect to the login page, so the “Secret Data” underneath is never shown until the user enters the correct login and password…

There is a little bit of hassle setting this up, but once you have- you can password protect any PHP file, just by adding one line!

Simple Lightbox-like effects with CSS and Javascript explained.

November 28th, 2008

Programming a lightbox-like effect with CSS and Javascript.

One way of really adding a professional touch to your website is with lightboxes. This is an effect where, when you have a popup, the rest of the website behind the popup darkens and blurs. A simplified version of the effect looks like this:

Screenshot from simple lightbox example

Screenshot from simple lightbox example

This effect is quite popular with Web 2.0 sites, and there are many libraries that allow you to use lightbox like effects. It doesn’t just look good to the visitors though- many people have found that the use of lightboxes will help with signups for their blog (if they use a signup form in the popup), or can even help with sales.

If you don’t want to use someone else’s library though (maybe because you’re worried about their size), you can implement your own lightbox surprising easily, with just a little CSS and Javascript.

Start by defining the CSS for the background. It looks like this:


#screenoverlay
{
	background-color: #CCCCFF; /* The color to display*/

	/* The transparency of the background */
	opacity: .75;
	filter: alpha(opacity=75);

	position: absolute;
	left: 0px;
	top: 0px;
	width: 100%;
	height: 100%;

	/* Set the overlay so it appears above the page content */
	z-index: 1000;
}

This CSS sets up the div we will use, so that it takes up the entire page (With the width/height 100% lines), and so that it appears above the rest of the page content (with the z-index line). You can change the color quite easily (Just alter the background-color line), and the transparency (or how “see-through” the overlay is), with the opacity and filter lines.

To use this CSS, we add the following just after the opening body tag.


	<div id="screenoverlay" style="visibility:hidden;"></div>

This will setup the overlay, and make sure that by default it is hidden. If you wish to see it while you are developing, you would just use this:


	<div id="screenoverlay"></div>

The next thing to do is setup the CSS for the popup itself. You can use various techniques for this- in this example I’ll just create a simple 200px X 200px, centered div.

The CSS for this is:


#topbox
{
	position: absolute;

	/* Default positioning, that will be overridden by the javascript */
	left: 0px;
	top: 0px;

	padding: 5px;
	width: 200px;
	height: 200px;
	background-color: #FFFFFF;

	/*Must use a z-index greater than the screen overlay*/
	z-index: 1001;
}

This sets up the div so that it is 200×200 (the width and height lines), has a white background, and is positioned in the top left corner. (The javascript will override this, so that the div is actually centered on the screen.)

Note the z-index: It’s important that this number is higher than the number for the screenoverlay, otherwise the popup will appear underneath instead of above.

Now we add the div to the HTML, right underneath the screenoverlay…


<div id="topbox" style="visibility:hidden;">
	<h3>Hey there!</h3>
	<a href='#' onclick="closeTop();return false;">Close</a>
</div>

This code adds the div to the page, and sets it to be hidden by default. The link code will call the javascript function ‘closeTop’ when it is clicked. (NB: Clicking the link wont actually go anywhere because of the ‘return false;’).

Underneath this, we add the normal page content.

You can bring up the popup any way you want, including mouse-overs, when a link is clicked, or using a delay. In this example, I’ll just bring up the popup when a link is clicked…


	<a href='#' onclick="showTop();return false;">
	Click here to display the lightbox...</a>

This calls the javascript function ’showTop’, when the link is clicked.

Now we get to the javascript functions. We only need 2, one to bring the popup up (showTop), and one to close it (closeTop).

At their simplest, these functions are just this:


<script type="text/javascript" language="javascript">
//<!--
function showTop()
{
	//Show the background overlay and topbox...
	document.getElementById('screenoverlay').style.visibility='visible';
	document.getElementById('topbox').style.visibility='visible';
}

function closeTop()
{
	//Hide the overlay and tobox...
	document.getElementById('screenoverlay').style.visibility='hidden';
	document.getElementById('topbox').style.visibility='hidden';
}
//-->
</script>

As you can see, the code just overrides the visibility of the CSS.

If you want to do anything more fancy, you can add extra code to showTop. If you wanted to actually change the popups content, you might set it by overriding innerHTML (eg: document.getElementById('topbox').innerHTML = ‘Hello World’;). In this example, we want to center the popup, so we will change showTop to…


function showTop()
{
	//Position the topBox. In this example I am just centering it on the screen
	boxWidth = 200;
	boxHeight = 200;

	screenWidth=document.all?document.body.clientWidth:window.innerWidth;
	screenHeight=document.all?document.body.clientHeight:window.innerHeight;

	xPos = (screenWidth - boxWidth) * 0.5;
	yPos = (screenHeight - boxHeight) * 0.5;

	document.getElementById('topbox').style.left=xPos;
	document.getElementById('topbox').style.top=yPos;

	//Show the background overlay and topbox...
	document.getElementById('screenoverlay').style.visibility = 'visible';
	document.getElementById('topbox').style.visibility = 'visible';
}

That’s it! Quite simple I think you’ll agree! Obviously you can add much more fancy effects, but hopefully now you understand the basics. If you want to see the example in action , click here.

Simple Ajax with PHP

November 17th, 2008

Ajax is a powerful system, allowing you to do things on your website which are similar to effects users take for granted with their desktop software.

One example of this is suggestions when people are typing things into a web form.

In this tutorial, I will show you how to do AJAX suggestions with PHP…

Start with an html file, and set it to the following:

<html>
<head>
	<script src="clienthint.js">
</head>
<body>
	<form>
		First Name:
		<input type="text" id="txt1"
		onkeyup="showHint(this.value)">
	</form>
	<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

This is just simple HTML code, that…

  • Includes a Javascript file
  • Creates a form, and sets the name to txt1
  • Creates a span, and sets the name to txtHint
  • Calls a javascript function showHint whenever a key is released.
The next thing to do is setup clienthint.js
The contents of this file are:
var xmlHttp

function showHint(str)
{
	if (str.length==0)
	{
		document.getElementById("txtHint").innerHTML=""
		return
	}
	xmlHttp=getHttpObject()
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}
	var url="gethint.php"
	url=url+"?q="+str
	xmlHttp.onreadystatechange=stateChanged
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function setField(str)
{
	document.getElementById("txt1").value=str
}

function stateChanged()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		document.getElementById("txtHint").innerHTML=xmlHttp.responseText
	}
}
function getHttpObject()
{
	var xmlHttp=null;
	try
	{
		//Standard compliant browsers
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		//IE
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

This file has the following functions:

  • getHttpObject, which gets an AJAX object from the current browser.
  • setField, which sets the text in the forms txt1 field.
  • showHint, which gets called by the javascript on the HTML page when a key is released in the form. It then calls the PHP file gethint.php
  • stateChanged, which receives the output from the PHP file, and sets the text in the span.
The final thing to do is setup the PHP file. It has the following content:
<?php

//The names to lookup
$names=array('Axel','Bart','Bob','Dan','Dillan','Doris','David','Millhouse');

$q=$_GET["q"];
$hint="";

$queryLength = strlen($q);

//lookup all hints from array if length of q>0
if ($queryLength > 0)
{
	foreach ($names as $name)
	{
		//Work out the name with the same number of characters
		$potentialName = substr($name,0,$queryLength);

		if (strtolower($q)==strtolower($potentialName))
		{
			$h = "<a href='#' onclick=\"setField('$name');return false;\">$name";
			if ($hint=="")
			{
				$hint=$h;
			}
			else
			{
				$hint=$hint." , ".$h;
			}
		}
	}
}

echo $hint;
?>

This file setups an array of string names. It then takes the input (which is the text the person has entered so far into the field), and compares it to the text names. If it finds a match, it outputs the name, inside a link, and sets it up so that when the link is clicked, the javascript function setField is called. (If you remember from before, setField will set the fields content in the form).

Thats it! It may sound a little complicated, but it will make your website seem way more professional, and it’s not that difficult really!

 

To see the demo in action, click the link below…
Ajax Demo1

Creating Rounded Boxes with CSS

November 8th, 2008

One of the biggest complaints about the web is that it is too square looking, with no curves.

It doesn’t have to be though. With clever use of CSS, you can quite easily make your pages look more rounded, which adds a certain level of quality to your pages.

It’s actually quite easy. In this tutorial, I will show you how to make a simple rounded box, like the one below…

CSS Rounded Boxes

Rounded boxes can make your site look much more interesting!

There are many ways to make a rounded box with CSS. In this tutorial I will show you the simplest way, and in future tutorials I will expand this to show you more flexible rounded boxes…

To start, we will create a regular box, and then make it rounded later. To do that, we put the block we want into a div, so it can be styled…

<div class='rounded_box'>
	<p>Rounded box content.</p>
</div>

We can then style the rounded box in CSS with this…

.rounded_box
{
	width: 300px;
	background:#FFFF99;
}

This will create a yellow square box, like this:

Rounded box content.

The next step is to round the bottom.

Start by creating an image like this:

Bottom image

Bottom image

(For details about how to do this in Gimp, click here)

No change the CSS, to be like this:

.rounded_box
{
	width: 300px;
	background:#FFFF99 url(rounded_bottom.png) no-repeat left bottom;
}

The background line sets the background to the background colour, with one copy of the image, in the bottom left corner of the box.

This will create a box that looks like this…

Rounded box content.

Now we want to add the rounded top. To do this, we need an image like this:

Top image

Top image

We now change the HTML to look like this:

<div class='rounded_box'>
<div class='rounded_top'></div>
	<p>Rounded box content.</p>
</div>

And add the following to the CSS…

.rounded_top
{
	background: url(rounded_top.png) no-repeat left top;
}

With this bit of CSS, whenever a “div class=’rounded_top’” is found in the HTML, it will uses our rounded top image, once, in the top left corner.

It now looks like this:

Rounded box content.

You might continue the example by applying padding to the p inside the rounded box, by adding the following CSS…

.rounded_box p
{
        padding: 0px 20px 40px 50px;
        margin: 0px;
}

The box now looks like this:

Rounded box content.

The complete code looks like this:


<style type="text/css">

.rounded_box
{
	width: 300px;
	background:#FFFF99 url(rounded_bottom.png) no-repeat left bottom;
}

.rounded_top
{
	background: url(images/rounded_top.png) no-repeat left top;
}

.rounded_box p
{
        padding: 0px 20px 40px 50px;
        margin: 0px;
}

</style>

<div class='rounded_box'>
<div class='rounded_top'></div>
	<p>Rounded box content.</p>
</div>

Rounded Box Tutorial for GIMP 2

November 8th, 2008

Rounded Box Tutorial for GIMP 2

Rounded boxes are a staple for website.  They allow the containment of content within an object that is both practical and appealing to look at.

1.
First create an image of whatever size you want, remember though to make the height double that of what you actually want the image to be, this will be explained later.  Here I’ve set the parameters to create an image that is 300 x 100px.

2.
Next you want to go to the image you just created and then go to Filters > Décor > Round Corners.  Make sure that Add Drop Shadow and Add Background are unticked, but that Work on Copy is ticked.

Settings to create rounded edges

Settings to create rounded edges

Ok, now once this is done you’ll have something that looks like the image below.

What the rounded edges should look like

What the rounded edges should look like

3.
Now, you should select the Paint Bucket tool and select which colour you would like to use.

Changing the colour

Changing the colour

The colour changing option, with the colour code used

The colour changing option, with the colour code used

The next thing is to click in the area of the rounded rectangle shape to fill it in with the colour you chose.

4.

This is where you see why you needed to make the image twice the height that it needed to be.  Select the Rectangle Select Tool and select the top half of the image, use the ruler guides on the sides to see where exactly half is.

Selecting half the image

Selecting half the image

Now cut this selection by going Edit > Cut and then create a new document.  With this document though set the height as being what you wanted it to be.  So in this case, I set it to be 50px.  Now paste the cut image into here and save it with the name Top or similar.

5.
To create the bottom of the box, go to Image > Transform > Flip Vertically.  Now save this as something along the lines of Bottom.

You now have the top and bottom images for use in content boxes on a website.  Below are the two images created.

Top image

Top image

Bottom image

Bottom image

Drop Shadow Tutorial for Photoshop CS2

October 29th, 2008

Drop Shadow Tutorial for Photoshop CS2

What Is a Drop Shadow?

A drop show is a visual effect that gives the illusion of the object casting it being raised above the surface below it.  This adds depth to an image and can make it appear to be more than just 2D at a glance.

How to Add One to Your Image

1.
Create a new Photoshop file, any size will do, even the default settings are good.

Options for Creating Image

Options for Creating Image

2.
Now the drop shadow will need to be based on something i.e. an object will be casting it.  Firstly, create a new layer for the object to go on.  Then, we need to create the object.  So for the easiest option, select the type tool and create a nice big letter.

The Object Creating the Drop Shadow

The Object Creating the Drop Shadow

3.
Ok, now we have our letter there, we are going to add the drop shadow effect to it. To do this, double click on the text layer and then select Drop Shadow and make sure the selection box is ticked.

The Options for The Drop Shadow

The Options for The Drop Shadow

4.
You can now play around with the different settings to achieve different effects. With my image I set the distance to 45px, the size to 5px, the angle to -135 and the opacity of the shadow to 55%.

Different Settings for The Drop Shadow

Different Settings for The Drop Shadow

As you can see, this has made quite a difference from what it was like in step 3.

This was just a simple tutorial to get you started on one of the basics of Photoshop. Play around with the settings to see all the different effects you can get.

Showing different google adsense adverts with PHP

October 29th, 2008

There are many benefits to knowing a little PHP. One of them is that you can easily add some simple little things to you website that can help make you a lot of money.

One example of this is using PHP to show different things randomly to different people on your site. You can use this for banner rotation, testing different versions of things of adverts/download links (called “Split testing”) and more. In this article I will show you you how you can use some simple PHP to randomly show different versions of adsense on your site, and find out which ad format is most profitable for your site.

For this example, lets suppose you want to test 2 different google adsense ad formats on your site, to see which one makes the most money…
- A 728 x 90 Leaderboard advert.

versus

- A 250 x 250 Square advert.

The PHP code to get a random number between 0 and 99 (inclusive) looks like this…

function getRand()
{
	return rand(0,99);
}

You can then get a random number in the php code at any time using…

$randomValue = getRand();

NB:You don’t really need to make this into a function, but it is a good idea to do so, because it makes it easier to do more advanced things later, such as showing the same version to the same person each time they visit the site (which I will cover in a future tutorial).

To display something based on the random number, you can do this:

<?php
if (getRand() % 2 == 0)
{
	echo 'Version1';
}
else
{
	echo 'Version2';
}
?>

This will display “Version 1″ to about half the people that view a page, and “Version2″ to the other half.

To display different versions of adsense ads, just replace “Version1″, and “Version2″ with the adsense code you wish to use. There is one thing to watch for, and that is that you can’t use the quote character(’) in your text. The google adsense code uses double quotes(”), so this isn’t a problem.

So your final version might become:

<?php
if (getRand() % 2 == 0)
{
	echo '
	script type="text/javascript"><!--
	google_ad_client = "pub-YOURADCLIENT";
	google_ad_slot = "ADSLOT1";
	google_ad_width = 728;
	google_ad_height = 90;
	//-->
	</script>
	<script type="text/javascript"
	src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
	</script>
	';
}
else
{
	echo '
	<script type="text/javascript"><!--
	google_ad_client = "pub-YOURADCLIENT";
	google_ad_slot = "ADSLOT2";
	google_ad_width = 250;
	google_ad_height = 250;
	//-->
	</script>
	<script type="text/javascript"
	src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
	</script>
	';
}
?>

You could use the above in a few simple steps:
- Paste it into your PHP file
- Change pub-YOURADCLIENT to your adclient (you can find this by viewing the google adsense code for your advert)
- Change ADSLOT1 and ADSLOT2 to your different ad slots.
- Make sure you have setup the adslots to use different adsense channels.

This will then display the different adverts randomly to people that visit the site. Leave it for a while, then look at your adsense stats, and find which channel has made more money, to know which advert is more effective for your site.

There is one problem with the code above- it doesn’t display the same advert type to a person each time they visit the site. I’ll show you how to solve this problem in a future tutorial…

Simple Setup for Windows-based Web Development

October 28th, 2008

Setting Up A Web Server

The best way to learn about how to use a web server, how one functions and how to maintain one is by running a local copy.

This can be quite hard as average home user machines running on Microsoft Windows are not setup or designed with this in mind. There are several programmes needed to have a fully functioning and accurate representation of what the website would look and function like when uploaded onto the internet.

At the very least the programmes needed are; Apache server, php and MySQL. At a later stage phpMyAdmin is useful but not necessary right at the start. Installing the three essential programmes can sometimes be confusing and downright frustrating having correct versions that won’t conflict.

A Simpler Solution

A simpler solution to this issue is the very handy tool known as WAMP. This integrates Apache, php and MySQL into one easy to install and use package. It makes running and maintaining a local server easier as it has and easy to navigate menu with all the controls needed at your finger tips.

WAMP can be downloaded from the download section of the WAMP website which is found at:

http://www.wampserver.com/

Once this has been found and the file has been downloaded, take the following steps:

  1. Double-click the installer file and follow the instructions, everything is automatic

  2. Double-click on the WAMP icon now visible on your desktop

Now you should have WAMP up and running.

Next navigate to My Computer > Drive you installed to > wamp

This is where WAMP has been installed and where you will find the rest of what you need. The most important file at the moment is the www directory. This is the directory where your website files will be put so that they can be accessed through your browser.

To access the website on your browser (as if it were uploaded to the internet), type http://localhost/nameoffolder/nameoffirstpage

You should now be able to see the page as if it were on an internet server.

PHP Hello World

October 28th, 2008

One of the first things most programmers write when they are learning a new language is a “hello world” program.

This is simply a program that write “hello world” onto the display. I’m not quite sure why this has become the traditional first program- it’s probably because it’s very quick to write, and usually easy to understand.

PHP is a popular server-side programming language, that is both powerful and easy to use. It’s run on the web server (ie: The machine where the website is stored), rather than the client’s computer, and is often used in combination with HTML.

PHP files usually have the extension “.php”. This tells the web server that the file may contain PHP statements (although it doesn’t have to have any PHP statements in it)

You start PHP statements with “<?php” and end with “?>”

So… on to the hello world program…

Create a file called hello.php and write the following using a text based editor (such as notepad)

<?php
echo 'Hello world';
?>

To run this file, you can either:
1- Go to a command prompt, and type php hello.php
2- Copy the file to a webserver, and visit hello.pho in the browser (This requires the server to have been setup with PHP. Most webhosts have this enabled, but if you are trying this on a local webserver, you may not have it setup)

The first line: “<?php”, starts the PHP statements
The second line: “echo ‘Hello world’;” writes ‘Hello World’ to the screen. Notice how it ends with ‘;’. All PHP statements must end with a semicolon.
The last line:”?>” ends the html.

Here is a slightly more complicated example:
Write the following in a file called hello2.php

<html>
Hello line 1<br>
<?php
echo 'Hello line 2<br>';
echo 'Hello line 3<br>';
?>
Hello Line 4
</html>

This example shows how easy it is to write multiple PHP statements. It also shows how you can easily integrate PHP into the middle of HTML content.