Saturday, August 22, 2009

Simple Encryption in PHP

Encryption using php?


A text or a password encryption can be done very easily using the functions md5() or sha1() or crypt() in php. It's a basic need to protect the password. The first step towards it is to encrypt it.

Text Encryption Using MD5 ( RSA's MD5 Message-Digest Algorithm ):


Example:

Original Text - This is test
Encrypted Text - fe1ca9859cefff19959d57aadc17187e

code:
<?php
$var = "This is test";
$enc = md5($var);
echo "Encrypted Text - $enc";
?>
On handling password, update the encrypted password in to database.
On login request, encrypt the password entered by user and compare it with the one in db.


Text Encryption Using SHA1 ( US Secure Hash Algorithm 1 ):


Example:
Original Text - This is test
Encrypted Text - 21650e52cb7a82638b93971684f6dcfceb14c9ab

code:
<?php
$var = "This is test";
$enc = sha1($var);
echo "Encrypted Text - $enc";
?>

On handling password, update the encrypted password in to database.
On login request, encrypt the password entered by user and compare it with the one in db.

Text Encryption Using Unix DES-based encryption algorithm :


Example:
Original Text - This is test
Encrypted Text - $1$tYQu2pZ5$s7mbrcnNzKFHZCrA5SXyJ/

code:
<?php
$var = "This is test";
$enc = crypt($var); //salt be automatically generated
echo "Encrypted Text - $enc";
?>

On handling password, update the encrypted password in to database.
On login request, use encrypt() as below to validate the password.
if (crypt($input, $password) == $password) {
echo "Password verified!"; }
where $input in user posted password and $password is the encrypted one in database.

Saturday, July 25, 2009

Ajax + PHP sample code

Function to create ajax object


AJAX stands for Asynchronous JavaScript and XML.

Ajax is a technology used to refresh a page content(or page area ) with out refreshing the whole page.AJAX is based on JavaScript and HTTP requests.We can use multiple ajax requestes on same page.

In the following example we are going to print some values from the server.

This function creates an ajax object. In these architecture we can use the same object for different ajax call. So multiple ajax object creation is not needed.It creates an XMLhttp object and return that object

Ajax object creation

function GetXmlHttpObject()
{
objXMLHttp = false;
try
{
objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
objXMLHttp = false;
}
}
if (!objXMLHttp && typeof XMLHttpRequest != 'undefined')
objXMLHttp = new XMLHttpRequest();
return objXMLHttp;
}

With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can receive data from the web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

All new browsers except IE5 and IE6 use the built-in JavaScript XMLHttpRequest object to create an XMLHttpRequest object (IE5 and IE6 uses an ActiveXObject).

Function to call ajax


This function calls the server page.First this function creates an ajax object by calling our function GetXmlHttpObject().

Call Ajax object

function callAjax()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
// Create a function that will receive data sent from the server
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
document.getElementById('resultdiv').innerHTML= xmlHttp.responseText;
}
}
xmlHttp.open("GET", "ajaxsample.php", true);
xmlHttp.send(null);

}
After a request to a server, we need a function to receive the data returned from the server.

The onreadystatechange property stores the function that will process the response from a server. The function is stored in the property to be called automatically.This function checks the ajax states.

Ajax States.

State Description
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

So after the 4 th state is completed, the javascript receives the result from the server.

Html file

Place the above javascript functions to the same html file

Web page


<script>
// place the above two functions here......
</script>

<form action="frmCheck" method="get">
<table width="445" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="74">&nbsp;</td>
<td width="365"><div id="resultdiv"></div></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="button" name="btnCheck" id="button" value="Check" onClick="callAjax();"></td>
</tr>
</table>
</form>

This html file contains the form values. While clicking the button it will call the "callAjax" function .

Server page (PHP page)


The ajax request the following page and it returns the value. We can use our own code here.

Server Page - ajaxsample.php


<?php
echo "ajax sample..";
?>

After running this page shows the text 'ajax sample..' on browser.

Tuesday, May 12, 2009

Print preview using javascript

Using javascript we can create printer friendly webpages.We can use window.print function to print a webpage.
The script is as follows.

<a href="javascript:window.print()">Click to Print This Page</a>

When we click on the print button a print dialog window will open and we can either print the page or can cancel the print. Using this method we cant find the preview of the print page. Using the following script we can generate a popup and the popup holds the data that has to be printed. So we can get print preview of the web page.

Step 1 : Create a div area that holds the print content.

example :

<div id="printsection">
<table width="652" border="0">
<tr>
<td width="30" height="24">&nbsp;</td>
<td width="606"><strong>This is a sample content for printing</strong></td>
</tr>
<tr>
<td height="129">&nbsp;</td>
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like.</td>
</tr>
</table>
</div>

here the div 'printsection' holds the print content.

Step 2 : Create a javascript function to open the popup

example :


<script language="javascript">
function printPage(printContent) {
var display_setting="toolbar=yes,menubar=yes,";
display_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
var printpage=window.open("","",display_setting);
printpage.document.open();
printpage.document.write('<html><head><title>Print Page</title></head>');
printpage.document.write('<body onLoad="self.print()" align="center">'+ printContent +'</body></html>');
printpage.document.close();
printpage.focus();
}
</script>

This function generates a window that contain the printing data.
Add the above code the <head> area. Here we can set the display settins like tool bar,menu bar , window height etc.

Step 3 : Call the function from the html page.

Call the above function from the html page.

example :

<a href="javascript:void(0);" onClick="printPage(printsection.innerHTML)">Print Preview</a>

That's all. It will popup a window and the print dialog box.

Full Source Code :

<html>
<head>
<title>Print Preview Sample</title>
<script language="javascript">
function printPage(printContent) {
var display_setting="toolbar=yes,menubar=yes,";
display_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";


var printpage=window.open("","",display_setting);
printpage.document.open();
printpage.document.write('<html><head><title>Print Page</title></head>');
printpage.document.write('<body onLoad="self.print()" align="center">'+ printContent +'</body></html>');
printpage.document.close();
printpage.focus();
}
</script>
</head>
<body>
<div id="printsection">
<table width="652" border="0">
<tr>
<td width="30" height="24">&nbsp;</td>
<td width="606"><strong>This is a sample content for printing</strong></td>
</tr>
<tr>
<td height="129">&nbsp;</td>
<td>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like.</td>
</tr>
</table>

</div>
<a href="javascript:void(0);" onClick="printPage(printsection.innerHTML)">Print Preview</a>
</body>
</html>


Sunday, May 10, 2009

Remove textbox value when click on textbox

We saw many search textbox contains the word 'search' and when we click on the text box the text will remove. We are using javascript to do this.


The code is as follows

<input type="text" onblur="javascript:if (this.value == '') { this.value = 'Search'; }" onfocus="javascript:if (this.value == ''Search'') { this.value = ''; }" value="'Search'" id="txtsearch" name="txtsearch">

Thursday, May 7, 2009

Pagination using PHP-MySQL

Simple pagination using PHP-MySQL

Paging means showing your query result in multiple pages instead of just put them all in one long page. Imagine waiting for five minutes just to load a search page that shows 1000 result. By splitting the result in multiple pages you can save download time plus you don't have much scrolling to do.

To show the result of a query in several pages first you need to know how many rows you have and how many rows per page you want to show. For example if I have 95 rows and I show 10 rows per page that mean I'll have ten pages (rounded up).So the pagination needs several steps to complete.

Step 1: Create a Database connection

Establish a database cconnection to execute the select query.
<?
DEFINE ('DB_USER', 'dbusername');
DEFINE ('DB_PASSWORD', 'dbpassword');
DEFINE ('DB_HOST', 'dbroot');
DEFINE ('DB_NAME', 'dbname');

$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
?>

Step 2:

Find the total number of records and the current page number. If the current page number is not specified then it tooks as first page. After that we can calculate the total number of pages.This is calculated by total records / row per page. For the first time the page value will be null, so by default we will set the limit to 10 and page to 1.
<?
extract($_GET);
// number of rows in one page
$page_rows = 10;
// this will find the total number of records in the table
$data = mysql_query("SELECT count(id) as totcount FROM user") or die(mysql_error());
$row_num = mysql_fetch_object($data);
$rows = $row_num->totcount;
// this function will find how much page is neded for pagination.
$last = ceil($rows/$page_rows);
if ($pagenum < 1)
$pagenum = 1;
elseif ($pagenum > $last)
$pagenum = $last;
?>
If this variables are not blank, i.e. if the users click on the next or previous or page links then the page number and number of items to displayed will be not null and we will display data accordingly.

Step 3:Listing the datas


After that we can display the selected values.
<?
$counter = $starter+1;
while($info = mysql_fetch_array( $data_p ))
{
?>
<tr >
<td height="21">&nbsp;</td>
<td><?=$count++?></td>
<td><?=$info['username'];?></td>
<td><?=$info['email']?></td>
</tr>
<?php
}
?>

Step 4

: Set up the previous,next options.
<?php
if ($pagenum != 1)
{
$previous = $pagenum-1;
?>
<a href="?pagenum=1" onclick=""> <<-First</a>&nbsp;&nbsp;
<a href="?pagenum=<?=$previous?>"> <-Previous</a>
<?php
}
?></td>
<td width="296">
<?php
if ($pagenum != $last)
{
$next = $pagenum+1;
?>
<a href="?pagenum=<?=$next?>" >Next -></a>&nbsp;&nbsp;
<a href="?pagenum=<?=$last?>" >Last ->></a>
<?php
}
?>
This area tells the user which page is currently being viewed, the total number of pages available, and contains links to go either forwards or backwards through the available pages. The hyperlinks are displayed as simple text if there are no previous or next pages. Note that these hyperlinks do not put the word FIRST, PREV, NEXT or LAST as a parameter in the URL string - they all specify an absolute page number in the format pagenum =value

Source Code

This is the complete source code
<?php
// will extract the GET value "pagenum"
extract($_GET);
// number of rows in one page
$page_rows = 10;
// data base connectivity code starts
$con = mysql_connect('localhost','root','');
if(!$con)
{
echo "could not connect";
}
mysql_select_db('test');
// data base connectivity code ends
// this will find the total number of records in the table
$data = mysql_query("SELECT count(id) as totcount FROM user") or die(mysql_error());
$row_num = mysql_fetch_object($data);
$rows = $row_num->totcount;
// this function will find how much page is neded for pagination.
$last = ceil($rows/$page_rows);
if ($pagenum < 1)
$pagenum = 1;
elseif ($pagenum > $last)
$pagenum = $last;
// this code find, the starting record of the table for SQL selection
$starter = ($pagenum - 1) * $page_rows;
$count = $starter+1;
$max = 'limit ' .$starter.',' .$page_rows;
// executing the query
$data_p = mysql_query("SELECT id,username,email FROM user $max") or die(mysql_error());
?>
<form name="frmpagination" method="post">
<table width="609" height="107" border="0" class="boarder" cellpadding="0" cellspacing="0">
<tr>
<td height="21">&nbsp;</td>
<td>&nbsp;</td>
<td colspan="2"></td>
</tr>
<tr>
<td width="14" height="21">&nbsp;</td>
<td width="55"><strong>Sl No</strong></td>
<td width="261"><strong>Name</strong></td>
<td width="279"><strong>Mail Id</strong></td>
</tr>
<tr>
<td colspan="4"><hr /></td></tr>
<?php
$counter = $starter+1;
while($info = mysql_fetch_array( $data_p ))
{
?>
<tr >
<td height="21">&nbsp;</td>
<td><?=$count++?></td>
<td><?=$info['username'];?></td>
<td><?=$info['email']?></td>
</tr>
<?php
}
?>
<tr>
<td height="21">&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td height="21">&nbsp;</td>
<td>&nbsp;</td>
<td colspan="2"></td>
</tr>
<tr>
<td height="21">&nbsp;</td>
<td colspan="3"><table width="600" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="43">&nbsp;</td>
<td width="253">
<?php
if ($pagenum != 1)
{
$previous = $pagenum-1;
?>
<a href="?pagenum=1" onclick=""> <<-First</a>&nbsp;&nbsp;
<a href="?pagenum=<?=$previous?>"> <-Previous</a>
<?php
}
?></td>
<td width="296">
<?php
if ($pagenum != $last)
{
$next = $pagenum+1;
?>
<a href="?pagenum=<?=$next?>" >Next -></a>&nbsp;&nbsp;
<a href="?pagenum=<?=$last?>" >Last ->></a>
<?php
}
?> </td>
</tr>
</table></td>
</tr>
</table>
</form>

Tuesday, April 21, 2009

How to store an array in a session?

Sometimes it's necessary to temporarily store data specific to a particular user while he/she surfs our website. For example, to make an admin control panel we have to check the admin session in every page.. PHP sessions provide you with just such a facility. We can store an array in a session variable. store multiple values with one reference we can use arrays, and can store these arrays in sessioon.
Sample code
<?php
session_start();
$_SESSION['admin']=array('adid'=>1,'adname'=>'main admin','privilage'=>'super','lastlogin'=>'12-May-2008');
?>
The above code will assign the array values to the session named 'admin'.
To view the array content
<?php
echo "<pre>";
print_r($_SESSION['admin']);
echo "</pre>";
// To get a particular element
echo "<pre>";
print_r($_SESSION['admin']['adname']);
echo "</pre>";
?>

To get all the values from the session array. This loop will list all elements in the session array.So we can use all these values using only one session.
<?php
foreach($_SESSION['admin'] as $key=>$value)
{
// it will print out the values
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

The output is :
The value of $_SESSION['adid'] is '1'
The value of $_SESSION['adname'] is 'main admin'
The value of $_SESSION['privilage'] is 'super'
The value of $_SESSION['lastlogin'] is '12-May-2008'

Sunday, January 25, 2009

Alternating table row colors

Here is a nice simple way of alternating table row colours.
The example is shown in PHP but the principal can be applied in any language.

Step 1 : First I create a very simple style for each row.
<style type=”text/css”>
.row1 { background: #000; color: #fff; }
.row0 { background: #fff; color: #000;}
</style>
Step 2 : Now I create a simple loop that prints my rows
<?php
print '<table>';
#Start at 0
$row = 0;
for ( $counter = 0; $counter <= 5; $counter ++)
{
$row = 1 - $row;
#Now I print the row with it’s css class name ‘row1' or 'row0′
print "<tr class=\"row$row\"><td>Row $row</td></tr>\n";
}
print '</table>';
?>

Source Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Colour Change sample</title>
<style type="text/css">
.row1 { background: #000; color: #fff; }
.row0 { background: #fff; color: #000;}
</style>
</head>
<body>
<?php
print '<table>';
#Start at 0
$row = 0;
for ( $counter = 0; $counter <= 5; $counter ++)
{
$row = 1 - $row;
#Now I print the row with it’s css class name ‘row1' or 'row0′
print "<tr class=\"row$row\"><td>Row $row</td></tr>\n";
}
print '</table>';
?>
</body>
</html>