Wednesday, January 27, 2010

How to resize an image in PHP


How to resize an image in PHP?




Following example shows you how to resize an image in PHP.





In some cases you may need to resize images in your web site. As an example create a profile picture from a large file. Using this PHP script you can resize an image to given width and height.
This can use when you create thumbnail images.

In this php code current date time is used to save the resized image.
You may need to create a directory named "images" in your application and another directory in it called "resized"
to save resized images.

Functions that are needed to resize an image using PHP

PHP function
Purpose
 file_exists ( string $filename )
 Checks whether a file exists.
getimagesize ( string $filename [, array &$imageinfo ] )
 determine the size of any given image file.
imagecreatefromgif ( string $filename )
 Create an image identifier using the image obtained from the given filename.
imagecreatefromjpeg ( string $filename )
 Create an image identifier using the image obtained from the given filename.
imagecreatefrompng ( string $filename )
 Create an image identifier using the image obtained from the given filename.
imagesx ( resource $image )
 Get the width of the given image resource.
 imagesy ( resource $image )
 Get the height of the given image resource.
 imagecreatetruecolor ( int $width , int $height )
 Create a new true color image of the specified size.
 imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
 Copies a rectangular portion of one image to another image
 imagegif ( resource $image [, string $filename ] )
 Creates the GIF file in filename from the image image.
 imagejpeg ( resource $image [, string $filename [, int $quality ]] )
 Creates a JPEG file from the given image.
 imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )
Outputs or saves a PNG image from the given image .


Bookmark and Share









1. Example code for resize an image using PHP.

PHP Code
<?php
class ImageResize{
private $image;

private $imageType;

private $imageHeight;

private $imageWidth;





function loadImageFile($image_path){

if(file_exists($image_path)){

$image_info=getimagesize($image_path);

switch(strtolower($image_info['mime'])){

case "image/gif":{

$this->imageType=IMAGETYPE_GIF;

$this->image=imagecreatefromgif($image_path);

}break;

case "image/jpeg":{

$this->imageType=IMAGETYPE_JPEG;

$this->image=imagecreatefromjpeg($image_path);

}break;

case "image/png":{

$this->imageType=IMAGETYPE_PNG;

$this->image=imagecreatefrompng($image_path);

}break;

default:{

die("Incompatible file type");

}

}

$this->imageWidth=imagesx($this->image);

$this->imageHeight=imagesy($this->image);

}else{

die("File does not exists");

}

}



function resizeImage($width,$height,$resizedImageName=''){

$resizedImage=imagecreatetruecolor($width,$height);

imagecopyresampled($resizedImage,$this->image,0,0,0,0,$width,$height,$this->imageWidth,$this->imageHeight);

$this->image=$resizedImage;



if($resizedImageName==''){

$resizedImageName="images/resized/".date('Y')."-".date('m')."-".date('d')."-".date('H')."-".date('i')."-".date('s');

}

switch($this->imageType){

case 1:{//gif

imagegif($this->image,$resizedImageName.".gif");

}break;

case 2:{//jpg

imagejpeg($this->image,$resizedImageName.".jpg",75);

}break;

case 3:{//png

imagepng($this->image,$resizedImageName.".png");

}break;

}

}

}


?>
How to use above image resize class in your php code?

$resize=new ImageResize();

$image_path="images/Image1.jpg";

$resize->loadImageFile($image_path);

$resize->resizeImage(80,80);
 



Useful  PHP Codes/Programs


 »   How to create random validation image in PHP
 »   How to get extension of a file using PHP
 »   How to upload and encrypt file in PHP
 »   How to upload files in PHP
 »   How to create arrays in PHP
 »   How to create thumbnail images in PHP
 »   How to connect MySQL Database in PHP


©-Copyright By Duminda Chamara 
JavaScript Validation  

Sunday, January 17, 2010

How to generate a random number in javascript


How to generate Random Numbers in JavaScript?




Following example shows you how to generate Random Numbers in JavaScript.





In some situations you may want to generate random numbers in your javascripts. The Math.random() method returns a floating-point number between 0 and 1. In this example shows how to create a simple game using javascript random numbers.




Demo- Generate Random Numbers using JavaScript.



JavaScript Random Number Generator
      
1. How to generate Random number between 1-10 ?   
2. How to generate Random number between 1-100 ?   
3. How to generate Random number up to entered integer value?    
Enter value  
  
 
Simple game using JavaScript Random Numbers
Guess a number and color. Then press Try button to check it.
       
 
Pick a number
 
Pick a color
   
     








1. Example code for generate random numbers using JavaScript.

JavaScript Code

<script type="text/javascript" language="javascript">

<!--

function getRandomNumber(randomUpTo){

var myRandomNumber=Math.floor(Math.random() * (randomUpTo+1));

alert(myRandomNumber);

}



function validateRandomNumberLimit(){

var txtField=document.getElementById("txtRandomNumberLimit");

var limit=txtField.value;



if(isNaN(limit)==false && limit>0){



}else{

txtField.value=5;

txtField.select();

}

}



function generateRandom(){

var limit=document.getElementById("txtRandomNumberLimit").value;//alert(limit);

getRandomNumber(parseInt(limit));

}



function checkSelection(){

var color=parseInt(document.getElementById("RadioGroupColors").value);

var number=parseInt(document.getElementById("RadioGroupNumbers").value);



var randomNumber=Math.floor(Math.random() * (5));

var randomColor=Math.floor(Math.random() * (4));



var colors=Array("Red","Green","Pink","Yellow","Black");

if(color==randomColor && number==randomNumber){

alert("Congratulations!\nYou are the winner");

}else{

alert("Sorry!\nPlease try again\nComuter selection was Number="+number+" Color="+colors[randomColor]);

}

}

-->

</script>

Html Code



<html>

 <head>

  <title>How to generate random numbers using JavaScript </title>

 </head>

<body>

<table border="0">

<tr>

<td align="left">1. How to generate Random number between 1-10 ? </td>

<td align="left">&nbsp;&nbsp;</td>

<td align="left"><label>

<input name="btnRandomNumber1" type="button" id="btnRandomNumber1" value="Get Random" onclick="javascript:getRandomNumber(11);" />

</label></td>

</tr>

<tr>

<td align="left" valign="top">2. How to generate Random number between 1-100 ? </td>

<td align="left">&nbsp;&nbsp;</td>

<td align="left"><input name="btnRandomNumber2" type="button" id="btnRandomNumber2" value="Get Random" onclick="javascript:getRandomNumber(100);" /></td>

</tr>

<tr>

<td align="left" valign="top">3. How to generate Random number up to entered integer value? </td>

<td align="left">&nbsp;</td>

<td align="left">&nbsp;</td>

</tr>

<tr>

<td align="left" valign="top"><table width="100%" border="0">

<tr>

<td>Enter value </td>

<td><label>

<input name="txtRandomNumberLimit" type="text" id="txtRandomNumberLimit" value="5" size="5" onkeyup="javascript:validateRandomNumberLimit();" />

</label></td>

<td>&nbsp;</td>

</tr>

</table></td>

<td align="left">&nbsp;&nbsp;</td>

<td align="left"><label>

<input name="btnRandomNumber3" type="button" id="btnRandomNumber3" value="Get Random" onclick="javascript:generateRandom();" />

</label></td>

</tr>

<tr>

<td colspan="3" align="left" valign="top">&nbsp; </td>

</tr>

</table>

</body>

</html>

 




 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript

©-Copyright By Duminda Chamara  
JavaScript Validation  

How to validate multiple checkbox in javascript

How to Validate Multiple Check Boxes in JavaScript?

Following example shows you how to validate multiple checkboxes using JavaScript as client side validation.
Multiple Check Boxes allows the user to select more than one item from the group. In some cases you may want to use multiple check boxes to make some selections. As a example you may need to select preferred subjects of a student(Maths, Science, English etc.). Some times you may want to select a features of a program using multiple check boxes. In such situations you should validate check box-selections before submitting the form. Use following multiple check box selection example to study the Multiple Checkboxes validation in JavaScript. This sample contains three Check Box Groups. First you have to select at least 3 mobile phone manufactures from first check box group. Then you have to select at least 4 features of the mobile phone. After that you have to select the camera resolution from the third multiple select check box. If you forget to make a selection from a check box group, you are prompted to make a selection from appropriate check boxes from that group. * In this example there are tow error message types used to indicate the error. Select one error message type in your program.




Demo- Validate Multiple Check Boxes Using JavaScript
Select at least three mobile phone manufactures.
Nokia Samsung
Panasonic    Sony Ericsson
Motorola Sharp
  
select at least 4 features.
FM Radio Email - SMTP, POP3 and IMAP4 Protocols
GPRS WAP 2.0/xHTML
Video Camera Java™
Bluetooth™ 3G
IR Voice Dialing
Select a camera resolution
1.0 Megapixel Camera
2.2 Megapixel Camera
3.0 Megapixel Camera
5.0 Megapixel Camera
  
Try it!

1. Example code for validate Multiple Check Boxes using JavaScript.

JavaScript Code
<script type="text/javascript" language="javascript"> <!-- function validateMultipleCheckBoxes(checkBoxGroupName,checkdBoxes,exactlyEqual,errorContainer,errorMessage){ var formName = "formCheckBoxValidator"; var form = document.forms[formName]; var noOfCheckBoxes = form[checkBoxGroupName].length; var isChecked = false; var checkedCheckBoxes = 0; for(var x=0;x<noOfCheckBoxes;x++){ if(form[checkBoxGroupName][x].checked==true){ checkedCheckBoxes++; } } if(exactlyEqual==true){ if(checkedCheckBoxes!=checkdBoxes){ document.getElementById(errorContainer).innerHTML=errorMessage; return false; }else{ document.getElementById(errorContainer).innerHTML=""; return true; } }else{ if(checkedCheckBoxes<checkdBoxes){ document.getElementById(errorContainer).innerHTML=errorMessage; return false; }else{ document.getElementById(errorContainer).innerHTML=""; return true; } } }
function validateCheckBox(){ var errorMessage="Error!\nInvalid Selection"; if(!validateMultipleCheckBoxes("mobilePhoneManufactures[]",3,false,"mobile_phones","Please select at least three<br>mobile phone manufactures")){alert(errorMessage);return false;} if(!validateMultipleCheckBoxes("checkBoxFeature[]",4,false,"features","Please select at least four<br>mobile phone features")){alert(errorMessage);return false;} if(!validateMultipleCheckBoxes("checkBoxCamera[]",1,true,"camera","Please select a camera resolution")){alert(errorMessage);return false;} alert("OK\nYour selection is valid!"); return true; } --> </script>
Html Code
<html>  <head>   <title>How to Validate Multiple Check Boxes Using JavaScript </title>  </head> <body>
<table table border="0" align="center" cellpadding="3" cellspacing="1" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px;background-color:#336600;"> <tr> <td bgcolor="#FFFFF0">Select at least three mobile<br /> phone manufactures. </td> <td bgcolor="#FFFFF0"><table width="100%" border="0"> <tr> <td align="left"><label> <input name="mobilePhoneManufactures[]" type="checkbox" id="mobilePhoneManufactures[]" value="checkbox" /> </label></td> <td align="left">Nokia</td> <td align="left"><input name="mobilePhoneManufactures[]" type="checkbox" id="mobilePhoneManufactures[]" value="checkbox" /></td> <td align="left">Samsung </td> </tr> <tr> <td align="left"><label> <input name="mobilePhoneManufactures[]" type="checkbox" id="mobilePhoneManufactures[]" value="checkbox" /> </label></td> <td align="left">Panasonic&nbsp;&nbsp;&nbsp;</td> <td align="left"><input name="mobilePhoneManufactures[]" type="checkbox" id="mobilePhoneManufactures[]" value="checkbox" /></td> <td align="left">Sony Ericsson</td> </tr> <tr> <td align="left"><label> <input name="mobilePhoneManufactures[]" type="checkbox" id="mobilePhoneManufactures[]" value="checkbox" /> </label></td> <td align="left">Motorola</td> <td align="left"><input name="mobilePhoneManufactures[]" type="checkbox" id="mobilePhoneManufactures[]" value="checkbox" /></td> <td align="left">Sharp</td> </tr>
</table> <label></label></td> <td bgcolor="#FFFFF0" id="mobile_phones" style="color:#FF0000;">&nbsp;&nbsp;</td> </tr> <tr> <td bgcolor="#FFFFF0"> select at least 4 fetures.</td> <td bgcolor="#FFFFF0"><table width="100%" border="0"> <tr> <td align="left"><label> <input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /> </label></td> <td align="left">FM Radio</td> <td align="left"><input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /></td> <td align="left">Email - SMTP,<br /> POP3 and IMAP4<br /> Protocols </td> </tr> <tr> <td align="left"><label> <input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /> </label></td> <td align="left">GPRS</td> <td align="left"><input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /></td> <td align="left">WAP 2.0/xHTML</td> </tr> <tr> <td align="left"><label> <input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /> </label></td> <td align="left">Video Camera </td> <td align="left"><input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /></td> <td align="left">Java&trade;</td> </tr> <tr> <td align="left"><label> <input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /> </label></td> <td align="left">Bluetooth&trade; </td> <td align="left"><label> <input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /> </label></td> <td align="left">3G</td> </tr> <tr> <td align="left"><label> <input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /> </label></td> <td align="left">IR</td> <td align="left"><label> <input name="checkBoxFeature[]" type="checkbox" id="checkBoxFeature[]" value="checkbox" /> </label></td> <td align="left">Voice Dialling</td> </tr> </table></td> <td bgcolor="#FFFFF0" id="features" style="color:#FF0000;">&nbsp;</td> </tr> <tr> <td bgcolor="#FFFFF0">Select a camera resolution </td> <td bgcolor="#FFFFF0"><table width="100%" border="0"> <tr> <td><label> <input name="checkBoxCamera[]" type="checkbox" id="checkBoxCamera[]" value="checkbox" /> </label></td> <td>1.0 Megapixel Camera </td> </tr> <tr> <td><label> <input name="checkBoxCamera[]" type="checkbox" id="checkBoxCamera[]" value="checkbox" /> </label></td> <td>2.2 Megapixel Camera </td> </tr> <tr> <td><label> <input name="checkBoxCamera[]" type="checkbox" id="checkBoxCamera[]" value="checkbox" /> </label></td> <td>3.0 Megapixel Camera </td> </tr> <tr> <td><label> <input name="checkBoxCamera[]" type="checkbox" id="checkBoxCamera[]" value="checkbox" /> </label></td> <td>5.0 Meagpixel Camera </td> </tr> </table></td> <td bgcolor="#FFFFF0" id="camera" style="color:#FF0000;">&nbsp;&nbsp;</td> </tr> <tr> <td bgcolor="#FFFFF0">&nbsp;</td> <td bgcolor="#FFFFF0">&nbsp;</td> <td bgcolor="#FFFFF0"><input name="btnValidateForm" type="button" id="btnValidateForm" value="Check Selection" onclick="javascript:validateCheckBox();"/></td> </tr> </table>
</body> </html>
 »   How to get screen resolution in JavaScript
 »   How to limit characters in textarea using JavaScript
 »   How to validate decimal number in JavaScript
 »   How to validate an email address in JavaScript
 »   How to validate date using JavaScript
 »   JavaScript String functions
 »   How to validate multiple select list box in JavaScript
 »   How to generate random numbers in JavaScript
 »   How to validate multiple check box in JavaScript
 »   How to validate user login in JavaScript
 »   How to validate drop down list in JavaScript
 »   How to validate radio button group in JavaScript
 »   How to create JavaScript alerts
 »    How to create popup windows in JavaScript
 »   How to count words in a text area using JavaScript
©-Copyright By Duminda Chamara  JavaScript Validation  

Sunday, January 10, 2010

how to validate user login

How to validate user login using MySQL with PHP and JavaScript?

Following example shows you how to validate user login in your web application.
Validate User Login with PHP,MySQL, and JavaScript
Suppose that you have a user login for your website or CMS. It is a best practice to validate user name and password before user press the login button. Because it prevents the additional request to your server. So it save your server resources. So you can check if the user has entered the user name and password before login. But keep in mind client side validation is not enough and you must do a server side validation for the login verification.In my example I used CSS for indicate errors. You can use JavaScript alert to ask to user to enter both user name and password before login. You can customize the login as your wish.

This is a complete example of user login validation. First of all you may need to know why to validate your login. Simply prevent unauthorized access to your account. Validation can do within several steps before send the request to the database server. Because hackers and several automated systems can send the large amount of request to the database server and make it busy or stuck the server. You can user JavaScript code to validate user name and password as client side validation. Also you can use a CAPTCHA verification code to determine the request actually comes from a human. As the 2nd step you can validate using a CAPTCHA code. So user must insert the text in the image correctly.

In this example I have used MySQLi library to database access. After user enter the CAPTCHA code correctly, you need to check the database for the entered user name as the 3rd step. So you have to design the database table for the user. In this table you have to store user_name, password, account creation time, last logged time,last logged IP address, number of login attempts. To build a more secure system you have to include above fields to your table. So you can check who is logged to the system and their IP address and logged time. They are very useful to determine unauthorized access to the system.

If user fails to enter his password correctly, you can assume that the login attempt from a hacker. So you can increase the number of logging attempts field by one. If the user fails 3 times to enter his password correctly, we can disable his user account temporally. Also in this step we can send a e-mail to the user regarding this login attempt. Then we can use other verification method such as SMS to reset the account. Even if the user successfully logged to the system, it is good idea to send a e-mail to the user including logged time and the IP address or country name. Every successful login, you have to reset the number of login attempt to the zero.

1. Validate user login using JavaScript as client side validation.

Copy and past bellow code as index.php. This is the file that use to login to the system.

Complete source code for validate user login
<?php
/*
Copyright by Duminda Chamara
http://kottawadumi.blogspot.com
*/
$message_id = (int)(isset($_REQUEST['message'])?(trim($_REQUEST['message'])!=''?$_REQUEST['message']:""):"");
if($message_id==1){
$message='User Name and password does not match';
}elseif($message_id==2){
$message='Your account has been disabled';
}else{
$message='&nbsp;';
}
?><!DOCTYPE HTML>
<html>
<head>
<title>Validate User Login</title>
<style type="text/css">
.login_form{border: 3px double #0080C0;background-color: #F8F8F8;border-radius: 5px 5px 5px 5px;font-family:Tahoma, Geneva, sans-serif;font-size:12px;padding:8px;margin-top:10%;background-image:url(../images/keys.png);background-repeat:no-repeat;background-position:right;width:270px;}
.login_form .title{font-size:14px;font-weight:bolder;margin-top:10px;}
.login_form input{border: 1px solid #0080C0;border-radius: 3px 3px 3px 3px;}
.login_form .error_input{border: 1px solid #FF0000;border-radius: 3px 3px 3px 3px;}
.login_form .message{color:#F00;}
</style>
<script type="text/javascript">
function validate_login(){
var user_name=document.getElementById("user_name");
var password=document.getElementById("password");
var error=0;
if(user_name.value.replace(/\s+$/,"")==""){
user_name.className='error_input';
error++;
}else{
user_name.className='';
}

if(password.value.replace(/\s+$/,"")==""){
password.className='error_input';
error++;
}else{
password.className='';
}

if(error>0){
document.getElementById("login_message").innerHTML="Please enter your login details";
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form id="userLogin" name="userLogin" action="login.php" method="post" onSubmit="javascript:return validate_login();">
<table border="0" align="center" cellpadding="2" cellspacing="0" class="login_form">
<tr>
<td colspan="3" class="title">Loign to the system</td>
</tr>
<tr>
<td align="right">User Name</td>
<td>:</td>
<td><input type="text" name="user_name" id="user_name" placeholder="User Name"></td>
</tr>
<tr>
<td align="right">Password</td>
<td>:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Login" id="Login" value="Login"></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td>&nbsp;</td>
<td id="login_message" class="message">&nbsp;<?php echo $message;?></td>
</tr>
</table>
</form>
</body>
</html>

2. My SQL code for creating user table.

This is the MySQL database backup of the user table. Copy bellow SQL code in to your preferred SQL editor and execute it. Or you can create it manually.



SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `site_users`
-- ----------------------------
DROP TABLE IF EXISTS `site_users`;
CREATE TABLE `site_users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(50) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL,
`last_logged_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_logon_ip` varchar(32) DEFAULT NULL,
`login_attempts` tinyint(4) DEFAULT NULL COMMENT '0',
`email_address` varchar(150) DEFAULT NULL,
`is_active` tinyint(4) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of site_users
-- ----------------------------
INSERT INTO `site_users` VALUES ('1', 'duminda', '202cb962ac59075b964b07152d234b70', null,

'127.0.0.1', '0', 'duminda@gmail.com', '1');
INSERT INTO `site_users` VALUES ('2', 'pami', '900150983cd24fb0d6963f7d28e17f72', null, null,

null, 'pamika@yahoo.com', '0');

3. PHP code for the validate user login with MySQL

Copy bellow code and save it as login.php file. Set your login form action to this file.



<?php
/*
Copyright by Duminda Chamara
http://kottawadumi.blogspot.com
*/

session_start();

$user_name = (isset($_POST['user_name'])?(trim($_POST['user_name'])!=''?$_POST['user_name']:""):"");
$password = (isset($_POST['password'])?(trim($_POST['password'])!=''?$_POST['password']:""):"");
$logged_ip = $_SERVER['REMOTE_ADDR'];

/*
If you are using CAPTCHA verification in your systems,
You can check the entered CAPTCHA code is correct or not.
if the CAPTCHA code is incorrect redirect to the login page.
*/

$mysqli = new mysqli("localhost", "root", "1234", "my_db");
if (mysqli_connect_errno()) { //Connection fail to the MySQL server
header("Location: index.php");
exit();
}else{
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `id`,password,login_attempts FROM site_users WHERE user_name=? AND is_active=?")){
$active_users_only=1;

/* bind parameters for markers */
$stmt->bind_param("si",$user_name,$active_users_only);
$stmt->execute();/* execute query */

$stmt->bind_result($user_id,$md5_password,$login_attempts);/* bind result variables */
$stmt->store_result();
//$stmt->fetch();/* fetch value */

if($stmt->num_rows>0){/*There is a record associated with entered user name*/
$stmt->fetch();
//echo $user_name." ".$user_id." ".$login_attempts;
if($login_attempts>2){
//Disable the user login
//Hear we can assume that someone try to hack this user account.
//So we can send a e-mail to the user regarding this
//Here we can user step two verification such as send SMS to the user with verification code


$mysqli->close();/* close connection */
header("Location: index.php?message=2");
exit();
}else{
if(md5($password)===$md5_password){//password matched
/*
Create session is_logged and assign 1
You can use this session variable to checked if the
User has logged in your rest of pages.
*/

$_SESSION['is_logged']=1;

/* Password and user name matched Login successful
Even if the login successful, we can send a e-mail to the
User including login time and country details
*/


//reset login attempts to 0
$query="UPDATE site_users SET login_attempts=0,last_logon_ip='".$logged_ip."' WHERE `id`=".$user_id;
$mysqli->query($query);

$mysqli->close();
header("Location: user.php");
exit();

}else{//password does not matched
/*Here we need to increase the login attempts to prevent hacking
If user fail to authorized his login with 3 attempts,
User account can disable temporally.
*/

$query="UPDATE site_users SET login_attempts=login_attempts+1 WHERE `id`=".$user_id;
$mysqli->query($query);
header("Location: index.php?message=1");
exit();
}
}
}else{
$stmt->close();/* close statement */
$mysqli->close();/* close connection */
header("Location: index.php?message=1");
exit();
}
}else{
$stmt->close();
$mysqli->close();
header("Location: index.php");
exit();
}
}

?>

4. Redirect to login successful page.

After a successful login you can redirect the user to user account. Keep in mind you have to check the session variable is_logged=0 before proceeding any action. That means you have check the session at the beginning of each file. Hackers may be try hijack your session Cookie to login to your account using XSS attacks. So you can check the session with the IP address for more secure login. But if the IP address frequently change, it is not a good solution. copy and save following code as user.php

code for the user page.

<?
/*
Copyright by Duminda Chamara
http://kottawadumi.blogspot.com
*/
session_start();
$is_logged = (isset($_SESSION['is_logged'])?$_SESSION['is_logged']:0);

if($is_logged!=1){
header("Location: index.php");
exit();
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Success</title>
</head>

<body>
<h1>You have Successfully Logged to the System</h1>
</body>
</html>

Download source code

Tuesday, January 5, 2010

JavaScript and PHP Examples

Latest JavaScript And PHP Examples

Home page Last updated: 2013, March 30

Are you a newcomer to web programming? As a newcomer to the web programming, you may need clear tutorials that are easy to understand. Congratulations now you are in the right place. There are lot of PHP, MySQL, and JavaScript related examples with live demos in this web site. All of these tutorials are free. There are very basic and some advanced tutorials which you need in your day to day programming life. Definitely you can gain good knowledge of fundamentals of JavaScript, PHP, and MySQL programming by referring this tutorial. Thank you for visiting this site!

Free JavaScript and PHP Tutorials

PHP is widely use for build dynamic websites. It is free and fast. Easy to learn. MySQL is the most common database server that use with PHP to develop database driven websites. JavaScript is widely use for interactive front-end development and real time client side validations.

Site Map
/ 24 Archives
Latest Code - Programming Help
Latest Code - Programming Help: March 2013
Latest Code - Programming Help: February 2013
Latest Code - Programming Help: January 2013
Latest Code - Programming Help: December 2012
Latest Code - Programming Help: November 2012
Latest Code - Programming Help: August 2011
Latest Code - Programming Help: July 2011
Latest Code - Programming Help: March 2011
Latest Code - Programming Help: November 2010
Latest Code - Programming Help: September 2010
Latest Code - Programming Help: June 2010
Latest Code - Programming Help: May 2010
Latest Code - Programming Help: April 2010
Latest Code - Programming Help: March 2010
Latest Code - Programming Help: February 2010
Latest Code - Programming Help: January 2010
Latest Code - Programming Help: December 2009
Latest Code - Programming Help: November 2009
Latest Code - Programming Help: October 2009
Latest Code - Programming Help: September 2009
Latest Code - Programming Help: August 2009
Latest Code - Programming Help: June 2009
Latest Code - Programming Help: October 2008
   
    
2009/
         
08/ 1 example
Latest Code - Programming Help
         
09/ 3 examples
Latest Code - Programming Help: How to create validation image in php
Latest Code - Programming Help: My SQL Database Connecting using PHP
Latest Code - Programming Help: How to Get File Extension of a file in PHP
         
10/ 2 examples
Latest Code - Programming Help: Get diffrent elements in two arrays
Latest Code - Programming Help: How to upload and encrypt a file in PHP
         
11/ 7 examples
Latest Code - Programming Help: How to upload files in PHP
Latest Code - Programming Help: How to create arrays in PHP
Latest Code - Programming Help: Validate Decimal Number
Latest Code - Programming Help: Get screen resolution in JavaScript
Latest Code - Programming Help: Limit characters in textarea
Latest Code - Programming Help: Decimal Number Validation in javascript?
Latest Code - Programming Help: Email Address Validation in Javascript
         
12/ 4 examples
Latest Code - Programming Help: Date validation using JavaScript
Latest Code - Programming Help: JavaScript validation
Latest Code - Programming Help: String functions in JavaScript
Latest Code - Programming Help: Validate Multiple-Select List Box
    
2010/
         
01/ 10 examples
Latest Code - Programming Help: How to validate Drop-Down list in JavaScript
Latest Code - Programming Help: how to validate user login
Latest Code - Programming Help: How to validate radio button group in JavaScript
Latest Code - Programming Help: How to validate Drop-Down list in JavaScript
Latest Code - Programming Help: JavaScript and PHP Examples
Latest Code - Programming Help: How to resize an image in PHP
Latest Code - Programming Help: How to generate a random number in javascript
Latest Code - Programming Help: How to validate multiple checkbox in javascript
Latest Code - Programming Help: How to connect MySQL database in PHP
Latest Code - Programming Help: how to validate user login
         
02/ 4 examples
Latest Code - Programming Help: How to create arrays in JavaScript
Latest Code - Programming Help: How to create javascript alerts
Latest Code - Programming Help: How to create a popup window
Latest Code - Programming Help: How to count words in a text area
         
03/ 5 examples
Latest Code - Programming Help: How to create text file in PHP
Latest Code - Programming Help: Array functions in PHP
Latest Code - Programming Help: How to create tree view/menu
Latest Code - Programming Help: How to automatically check multiple checkboxes
Latest Code - Programming Help: How to create tree view/menu
         
04/ 1 example
Latest Code - Programming Help: How to create cookies in JavaScript
         
05/ 6 example
Latest Code - Programming Help: how to validate textbox using javascript
         
06/ 5 example
Latest Code - Programming Help: How to create xml file in php
         
09/ 1 example
Latest Code - Programming Help: Validate form in JavaScript
         
11/ 2 examples
Latest Code - Programming Help: php file system functions
Latest Code - Programming Help: Change style property using JavaScript
    
2011/
         
03/ 1 example
Latest Code - Programming Help: How to validate email address in php
         
07/ 1 example
Latest Code - Programming Help: Add or remove list box items dynamically in javascript
         
08/ 1 example
Latest Code - Programming Help: How to check domain availability in php
    
2012/
         
11/ 1 example
Latest Code - Programming Help: How to get ip address of a website
         
12/ 5 examples
Latest Code - Programming Help: PHP Random password generator
Latest Code - Programming Help: change text case in JavaScript
Latest Code - Programming Help: JavaScript charAt() method
Latest Code - Programming Help: JavaScript random password generator
Latest Code - Programming Help: How to parse URL in php
    
2013/
         
01/ 3 examples
Latest Code - Programming Help: Generate random numbers in php
Latest Code - Programming Help: Read image metadata using PHP
Latest Code - Programming Help: redirect url using javascript
         
02/1 example
Latest Code - Programming Help: Create captcha image in php
         
03/ 1 example
Latest Code - Programming Help: Create compressed zip file in PHP