Sunday, March 29, 2009

Centering your web page via a div

I center my websites in the browser and normally have the site width set to 950 pixels.

To center I create a div with the following class='wrapper', the style will be 

.wrapper {
width: 950px;
margin: 0 auto;
}

As IE as issues with the above we enter into the body tags, style="width: 100%; text-align: center;"

Monday, March 9, 2009

PHP Sessions

A Session stores temporary data on the server for later use while on a website, the session data is destroyed after the website has been closed.

Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage.

I use sessions after I have verified the log on details of an user. The user is able to access allowed pages. Any one not logged in will get a message say that they are not authorised.

All page that require the use of a session, even the original log on page must have this code.

session_start();
header("Cache-control: private");
// Allows the backspace of a page will in a session

Once I have verified the user logging in I would place this code.

if($user = 'user' && $pass = 'password') // This section of code is a simple example to show
{
$_SESSION['name'] = true; // Names the session for later use.
echo "Your are logged in";
}
else
{
echo "Incorrect username or Password";
}

All pages that the user has permision will nee the following code:

session_start();
header("Cache-control: private");


if($_SESSION['name'])
{
echo "You have access to this page"; // Plus all the information that the only the user can is autorised to see.
}
else
{
echo "You are not authorised to see the contents of this page";
}

Sunday, March 8, 2009

Number of Rows in Database Function

Have created a function that will query a database and return the number of rows as a result of the query.

I use this function as part of log in access of myweb site. The first section of code is on the log in page.

$username = $_POST['usernamel'];
$password = $_POST['password'];

include "functionfile.php";

$rowqry = "SELECT * FROM tablename WHERE username = '$username' AND password = '$password' ";
if(numofrows($rowqry) == 1)  // calling the fuction and checking that the results equal 1
{
// if result is correct add the info that you want to display here
}
else
{
echo "Your password or username may be incorrect, please try again";
}

This is the function that is called, I have a single fill (functionfile.php) with all my functions that I include in the code.

function numofrows($rowqry)
{
$host = "localhost"; // database host
$un = "username"; // database username
$pw = "password"; // database password
$dbname = "database"; // database name
$dbase = mysql_connect($host, $un, $pw);
if (!$dbase)
die ( "No Connection"); // connecting to database
mysql_select_db($dbname, $dbase)
or die ("Could not open $dbname: ".mysql_error()); // Opening database
$result = mysql_query($rowqry, $dbase); // applying query to database
$rows = mysql_num_rows($result); // counting rows in the applied query
return $rows; // returns result to fuction
}

Thursday, March 5, 2009

PHP Form, Code Injection

A HTML form, can be used to inject a piece of code to produce results that the hacker wants. An unprotected  form can be used to run a simple php code like ' echo "hello world";'  or a more destructive code.... 

To stop the form from being hacked I use the following steps:

Step 1. Check the data via JavaScript;

Call the JavaScript function by putting onsubmit='return checkform()' in the form tags

The folowing code checks that the password is alpha numerical, and if so returns and processes the form. The main reaon for the JavaSrcipt is to validate the form for the standard user, making sure that the correct data format is entered.

function checkform()
{
re = "no";
repass = /^[0-9A-Za-z]+$/;
if(repass.test(document.form.password.value))
{
re='yes';
}
else
{
alert('Please make sure the password is alpha numeric');
document.form.password.select();
document.form.password.focus();
return false;
}
if(re=="yes")
{
return true
}
}

Step 2.  Check the data via PHP

This code recieves the data from the forms textbox, makes sure that the data is alpha numeric. If the data is not apha numeric the error message is displayed, and the code stops running. 

The main purpose for this extra code, is that the hacker would not be using the form provided, thus rendering the JavaScript useless, so if a hacker or spammer enters any thing but numbers or letters then the code will cease.

$pw = $_POST['password'];

$passpattern = '/^[0-9A-Za-z]+$/';

$errormessage = " field, has invalid information and needs to be changed.";

if (!preg_match("$passpattern", "$pw")) 
{
echo "Your Password $errormessage"; 
exit();
}

Step 3. Preparing the data for MYSQL

The mysql_escape_string() function replaces characters that have a special meaning in MySQL with an escape sequence. eg " is replaced with \" and ' is replaced with \'. This will stop any code being written to the database and executed as it will be displayed as plain text.

If you use  mysql_real_escape_string() as the preffered alternative then you will need to be connected to the database before you run the code.

$pw = mysql_escape_string($pw);

Step 4. Use my examples as a basis to do your own research, and if find and alternative please post.

Wednesday, February 25, 2009

Regular Expresions JavaScript

My list of Regular Expressions used in validating forms using JavaScript
  • Checking Email Addresses,
    remail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;   
  • Checking a persons name,
    rename = /^((?:[A-Z](?:('|(?:[a-z]{1,3}))[A-Z])?[a-z]+)|(?:[A-Z]\.))(?:([ -])((?:[A-Z](?:('|(?:[a-z]{1,3}))[A-Z])?[a-z]+)|(?:[A-Z]\.)))?$/;
  • Checking the contents of a message or text box to make sure that only the characters intend are being used,
    remess = /^[0-9A-Za-z\,\.\'\-\s]+$/;

Sunday, February 22, 2009

Contact form Javascript

This JavaScript has 3 functions, the first checks the details entered into the contact form an should the criteria be met, the form is processed.

The second and third functions count down the characters entered in to a texarea

I use this JavaScript in conjunction with the post Adding PHP Contact Form


function Contact()
{
re = "no";
remail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
rename = /^((?:[A-Z](?:('|(?:[a-z]{1,3}))[A-Z])?[a-z]+)|(?:[A-Z]\.))(?:([ -])((?:[A-Z](?:('|(?:[a-z]{1,3}))[A-Z])?[a-z]+)|(?:[A-Z]\.)))?$/;
remess = /^[0-9A-Za-z\,\.\'\-\s]+$/;
if(rename.test(document.contact.name.value))
{
re="yes";
}
else
{
alert("Please check your name");
document.contact.name.select();
document.contact.name.focus();
return false;
}
if(remail.test(document.contact.email.value))
{
re="yes"
}
else
{
alert("Please check your email address");
document.contact.email.focus();
document.contact.email.select();
return false
}
if(remess.test(document.contact.question.value))
{
re="yes";
}
else
{
alert("Please check your Message");
document.contact.question.select();
document.contact.question.focus();
return false;
}
if(re=="yes")
{
return true
}
}

function getObject(obj)
{
var theObj;
if(document.all)
{
if(typeof obj=="string")
{
return document.all(obj);
}
else
{
return obj.style;
}
}
if(document.getElementById)
{
if(typeof obj=="string")
{
return document.getElementById(obj);
}
else
{
return obj.style;
}
}
return null;
}


function Contar(entrada,salida,texto,caracteres)
{
var entradaObj=getObject(entrada);
var salidaObj=getObject(salida);
var longitud=caracteres - entradaObj.value.length;
if(longitud <= 0)
{
longitud=0;
texto=' '+texto+' ';
entradaObj.value=entradaObj.value.substr(0,caracteres);
}
salidaObj.innerHTML = texto.replace("{CHAR}",longitud);
}

Saturday, February 21, 2009

Named Anchors

A named anchor works like a bookmark on a page, if you have a page with a lot of text and want to browse to a position on the page, a named anchor will help

Below is the link that directs you to the anchor



The anchor should be placed above the text you want to browse to.

Thursday, February 19, 2009

Adding a php contact form

Create a form with the action calling itself, and the method is POST

The form should have 2 input text boxes named, name, email and a textarea named question

Have added some JavaScript information to validate the contents of the form, at this post 

Add the folowing to the start of the php file

$name = $_POST['name'];
$email = $_POST['email'];
$question = $_POST['question'];
$emailto = "email@yourwebsite.com";

Include the following to call a function

include "function_contact_form.php";
contact_form($name,$email,$question,$emailto);

Create a file called function_contact_form.php and add the text below.

function contact_form($name,$email,$question,$emailto)
{
$myemail = $emailto;

$subject = "Ask A Question";

$message = "From: $name ($email) \n
Question: $question \n";

$from = "From: $email\r\n";

$spamerrormessage = "A web site URL has been detected, the form submission has been cancelled";
if (preg_match("/http/i", "$name")) 
{
echo " $spamerrormessage"; 
exit();
}
if (preg_match("/http/i", "$email")) 
{
echo " $spamerrormessage";
exit();
}
if (preg_match("/http/i", "$message")) 
{
echo " $spamerrormessage"; 
exit();
}


if ($myemail !="")
mail ($myemail, $subject, $message, $from);
echo "Thank You $name for your inquiry.";
}