Friday, 31 May 2013

Javascript code to match password and re-enter password

Simple Javascript Code to match password and confirm password



CODE :


<script>
function check()
{
  if(document.f1.pwd.value != document.f1.cpwd.value)
  {
  document.getElementById("res").innerHTML="<font color='red'>pwd and cpwd does not match</font>";
  }
  else
  {
  document.getElementById("res").innerHTML="<font color='green'>pwd and cpwd are matched</font>";
  }
}
</script>

<h2>Password And Confirm Password Match Tutorial</h2>

<form action="" method="post" name="f1">
<p>User Password : <input type="password" name="pwd" placeholder='enter password'></p>
<p>Re-enter Password : <input type="password" name="cpwd" placeholder="re-enter password" onkeyup="check()">&nbsp;&nbsp;<span id="res"></span></p>
</form>


For maore tutorials vasit on blog phpedu108.blogspot.in


Ouput Of Above Code

Password And Confirm Password Match Tutorial

User Password :

Re-enter Password :   





File System or File Handling in PHP


File System or File Handling in php

One of the most useful features of a server side language is its ability to interface with the file system on the server that hosts the website.
  File system is a linear approach.
In php we create a web application without using rdbms(relational database management system ) by using file system.
In file system or file handling we working with diffrent types files and directories or folders.

WORKING WITH FILES-

HOW TO CREATE A FILE-

To create a file in php we use function touch()

syntax :

touch($filename);

and another method to create a file is

syntax :


fopen($filename,"w");

Ex-

<?php
touch("test.pdf");
?>

output :

its create a pdf file of name test in current directory.

HOW TO DELETE A FILE-

To delete a file in php we use function unlink()

syntax :

unlink($filename);

Ex-

<?php
unlink("test.pdf");
?>

output :

its delete a pdf file of name test in current directory.

HOW TO ACCESS FILES-

To access a file you first have to establish a connection to that file.  This is done by opening the file with the fopen function. 
 To use the fopen function you provide it two parameters.
  The first is the name of the file you wish to use
 and the second says how you want to use the file (for reading or writing, etc.) 

 Using the fopen function establishes a pointer to the file.  Here's an example:

<?php
$myfilepointer = fopen("myfilename.txt", "w");
?>

here, we're opening a file called "myfilename.txt" and saying that we wish to write to it.  The "w", which is what tells PHP we want to write to the file, is called the Access Mode.  Other values that can be used, and their meanings are:

r read only

r+ reading and writing

w write only & create the file if it doesn't exist

w+ reading and writing & create the file if it doesn't exist

a writing only, create if it doesn't exist, and place a file position pointer at the end of the file (appends records to an existing file)


a+ reading and writing, create if it doesn't exist and place file position pointer at the end of the file



HOW TO WRITE A FILE :

When writing to a file, the first thing you need to do is to open up the file. We do that with this code:

 <?php 
 $File = "YourFile.txt"; 
 $Handle = fopen($File, 'w');
 ?>

Now we can use the fwrite command to add data to our file. We would do this as shown below:

 <?php 
 $File = "YourFile.txt"; 
 $Handle = fopen($File, 'w');
 $Data = "Jane Doe\n"; 
 fwrite($Handle, $Data); 
 $Data = "Bilbo Jones\n"; 
 fwrite($Handle, $Data); 
 print "Data Written"; 
 fclose($Handle); 
 ?>

ANOTER WAY TO WRITE A FILEEX-

<?php
$file = 'REX.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
file_put_contents($file, $person, FILE_APPEND );
?>

HOW TO READ A FILE :

USE OF fread()

Definition: Fread () reads data from an external file and reports it back to your PHP file. It read the number of bytes that you specify. It is phrased as: fread ( handle, length ). You must open the file in the handle. The length is measured in bytes, with a 8192 byte maximum.

Also Known As: file read, php file read

Examples:

<?php
 $myFile = "MyFileName.txt"; 
 $handle = fopen($myFile, 'r'); 
 $Data = fread($handle, 10); 
 fclose($handle); 
 echo $Data;
 ?>

USE OF fgets()

Definition: The PHP function fgets () is used to read a file line by line. This will only work if the file data is stored on separate new lines, if it is not this will not produce the results you are looking for. It is phrased as: fgets (handle, length). The File must be opened in the handle. Length does not need to be included, but it will default to 1024 bytes if it is not specified.

Examples:

 <?php 
 $myFile = "YourFile.txt"; 
 $handle = fopen($myFile, 'r'); 
 while (!feof($handle)) 
 { 
 $data = fgets($handle, 512); 
 echo $data; 
 echo "<br>"; 
 } 
 fclose($handle); 
 ?> 
USE OF file_get_content()
Definition: File_Get_Contents () works the same as file () except it returns a string instead of an array. This function retrieves data from an external file and then puts it into a string for use.
Examples:
 <?php 
 $file = file_get_contents ('rex.txt'); 
 Echo $file;
 ?> 
HOW TO RENAME A FILE :
USE OF rename()
Definition: rename () is used to rename a file:
Syntax :
rename($currentFileName,$newFileName);
Ex-
<?php
//which rename the text file of name rex into text file of name test
rename("rex.txt","test.txt");
?>

HOW TO COPY A FILE :
USE OF copy()
Definition: rename () is used to copy a file from destination  to source address:
Syntax :
copy("destination/$FileName","target/$FileName);
Ex-
<?php
//which copy the text file of name rex into folder new which placed in current directory.
rename("rex.txt","new/rex.txt");
?>


WORKING WITH DIRECTORIES
PHP directories functions are provided to manipulate any directory.
List of Functions
Function chdir()
Definition and Usage
Changes PHP's current directory to the passed directory.
Example
Following is the usage of this function:
<?php
// current directory
echo getcwd() . "\n";
chdir('html');
// current directory
echo getcwd() . "\n";
?> 
This will produce following result:
/home/tutorialspoint
/home/tutorialspoint/html

Function chroot()
Definition and Usage
Changes the root directory of the current process to the passed directory.
<?php
chroot('/var/www');
?> 

Function dir()

Definition and Usage


The dir() function opens a directory handle and returns an object. The object contains three methods called read() , rewind() , and close() .

<?php
$d = dir("/var/www/");
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();
?> 

Function opendir() AND readdir()

Definition and Usage

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Example

Following is the usage of this function:

<?php
//Open images directory
$dir = opendir("/var/www/images");
//List files in images directory
while (($file = readdir($dir)) !== false)
{
  echo "filename: " . $file . "<br />";
}
closedir($dir);
?> 

This will produce following result:

filename: .
filename: ..
filename: logo.gif
filename: mohd.gif

Function scandir()

Definition and Usage

Returns an array of files and directories from the passed directory.

<?php
$dir   = 'new';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
//print_r($files2);
?> 


                                     



Thursday, 30 May 2013

Object Oriented Programming in PHP

Object Oriented Programming in php

A simple and short PHP tutorial and complete reference 

manual for all built-in PHP functions. This tutorial is 

designed for php begners for working with object 

oriented php.




CREATE TABLE users
(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
password VARCHAR(50),
name VARCHAR(100),
email VARCHAR(70) UNIQUE
);


Create php page       

config.php

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
class DB_Class
{
function __construct()
{
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or
die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection)
or die('Database error -> ' . mysql_error());
}
}
?>



Create  Another php page       

function.php

<?php
include_once 'config.php';
class User
{
//Database connect 
public function __construct()
{
$db = new DB_Class();
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////



//Registration process 


public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}




//////////////////////////////////////////////////////////////////////////////////////////////////////////////////


// Login process



public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return TRUE;
}
else
{
return FALSE;
}
}



////////////////////////////////////////////////////////////////////////////////////////

// Getting name


public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
// Getting session 
public function get_session()
{
return $_SESSION['login'];
}
// Logout 
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}

}
?>



Create php page       

registration.php

<?php
include_once 'include/functions.php';
$user = new User();
// Checking for user logged in or not
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$register = $user->register_user($_POST['name'], $_POST['username'], $_POST['password'], $_POST['email']);
if ($register)
{
// Registration Success
echo 'Registration successful <a href="login.php">Click here</a> to login';
} else
{
// Registration Failed
echo 'Registration failed. Email or Username already exits please try again';
}
}
?>


//HTML Code
<form method="POST" action="register.php" name='reg' >
Full Name
<input type="text" name="name"/>
Username
<input type="text" name="username"/>
Password
<input type="password" name="password"/>
Email
<input type="text" name="email"/>
<input type="submit" value="Register"/>
</form> 




Create php page       

login.php

<?php
session_start();
include_once 'include/functions.php';
$user = new User();
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$login = $user->check_login($_POST['emailusername'], $_POST['password']);
if ($login)
{
// Login Success
header("location:login.php");
}
else
{
// Login Failed
$msg= 'Username / password wrong';
}
}
?>


//HTML Code
<form method="POST" action="" name="login">
Email or Username
<input type="text" name="emailusername"/>
Password
<input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>



Create php page       

home.php

<?php
session_start();
include_once 'include/functions.php';
$user = new User();
$uid = $_SESSION['uid'];
if (!$user->get_session())
{
header("location:login.php");
}
if ($_GET['q'] == 'logout')
{
$user->user_logout();
header("location:login.php");
}
?>
//HTML Code
<a href="?q=logout">LOGOUT</a>
<h1> Hello <?php $user->get_fullname($uid); ?></h1> 

Wednesday, 29 May 2013

Refrence Variable in php

Refrence Variable 

Any variable will be called reference variable, if it contains another variable as its value.





Example :


<?php

$rex = "max";

$$rex = "www";

echo $max;

?>


Output :
           www

How to unziped a directory using php

Extract a Zip File Using PHP

   In my previous post i had posted how you can make a zip file in Php. But i know many of you are also looking to unzip a zip file in php. So here i am back with the solution.



CODE : (PHP SIMPLE CODE TO EXTRACT A ZIPED DIRECTORY)



<?php
$zip = new ZipArchive;
if ($zip->open('rex.zip') === TRUE) {
    $zip->extractTo('res/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

Create zip file using php

Create a Zip File Using PHP
Creating .ZIP archives using PHP can be just as simple as creating them on your desktop. PHP's ZIP class provides all the functionality you need! To make the process a bit faster for you, I've coded a simple create_zip function for you to use on your projects.


Example :

Step-1

         Create a directory of name files include two image files 
       files ->flowers.jpg, fun.jpg

Step-2

        test.php


<?php
$error = ""; //error holder
if(isset($_POST['createpdf'])){
$post = $_POST;
$file_folder = "files/"; // folder to load files
if(extension_loaded('zip')){ // Checking ZIP extension is available
if(isset($post['files']) and count($post['files']) > 0){ // Checking files are selected
$zip = new ZipArchive(); // Load zip library
$zip_name = time().".zip"; // Zip name
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ // Opening zip file to load files
$error .=  "* Sorry ZIP creation failed at this time<br/>";
}
foreach($post['files'] as $file){
$zip->addFile($file_folder.$file); // Adding files into zip
}
$zip->close();
/*if(file_exists($zip_name)){
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
readfile($zip_name);
// remove zip file is exists in temp path
unlink($zip_name);
}*/
}else
$error .= "* Please select file to zip <br/>";
}else
$error .= "* You dont have ZIP extension<br/>";
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create Zip</title>
</head>
<body>
<center><h1>Create Zip</h1></center>
<form name="zips" method="post">
<?php if(!empty($error)) { ?>
<p style=" border:#C10000 1px solid; background-color:#FFA8A8; color:#B00000;padding:8px; width:588px; margin:0 auto 10px;"><?php echo $error; ?></p>
<?php } ?>
<table width="600" border="1" align="center" cellpadding="10" cellspacing="0" style="border-collapse:collapse; border:#ccc 1px solid;">
  <tr>
    <td width="33" align="center">*</td>
    <td width="117" align="center">File Type</td>
    <td width="382">File Name</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" name="files[]" value="flowers.jpg" /></td>
    <td align="center"><img src="files/flowers.jpg" title="Image" width="16" height="16" /></td>
    <td>flowers.jpg</td>
  </tr>
  <tr>
    <td align="center"><input type="checkbox" name="files[]" value="fun.jpg" /></td>
    <td align="center"><img src="files/fun.jpg" title="Image" width="16" height="16" /></td>
    <td>fun.jpg</td>
  </tr>
  
  <tr>
    <td colspan="3" align="center">
    <input type="submit" name="createpdf" style="border:0px; background-color:#800040; color:#FFF; padding:10px; cursor:pointer; font-weight:bold; border-radius:5px;" value="Download as ZIP" />&nbsp;
        <input type="reset" name="reset" style="border:0px; background-color:#D3D3D3; color:#000; font-weight:bold; padding:10px; cursor:pointer; border-radius:5px;" value="Reset" />
    </td>
    </tr>
</table>

</form>
</body>
</html>

Tuesday, 28 May 2013

Super Global Variable $_SERVER In PHP

$_SERVER

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.

'PHP_SELF'


The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar.

Ex-If  Page address is 'localhost/auto/8-00/test.php'

<?php
echo $_SERVER['PHP_SELF'];
?> 

Output :

/auto/8-00/test.php

'SERVER_NAME'

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

Ex-If  Page address is 'localhost/auto/8-00/test.php'

<?php
echo $_SERVER['SERVER_NAME'];
?> 

Output :

localhost

'SERVER_SOFTWARE'

It provide information about server softwares.


Ex-

<?php
echo $_SERVER['SERVER_SOFTWARE'];
?> 

Output :

Apache/2.2.12 (Win32) DAV/2 mod_ssl/2.2.12 OpenSSL/0.9.8k mod_autoindex_color PHP/5.3.0 mod_perl/2.0.4 Perl/v5.10.0

Monday, 27 May 2013

Server Side Form Validation using php

Server Side Form Validation using php


Server Side Form Validation Demo given below.


CODE :


<?php
if(isset($_POST['Submit'])){

$name=trim($_POST["name"]);
$number=trim($_POST["number"]);
$email=trim($_POST["email"]);

if($name == "" ) {
$error= "error : You did not enter a name.";
$code= "1" ;
}

elseif($number == "" ) {
$error= "error : Please enter number.";
$code= "2";
}

//check if the number field is numeric
elseif(is_numeric(trim($_POST["number"])) == false ) {
$error= "error : Please enter numeric value.";
$code= "2";
}

elseif(strlen($number)<5) {
$error= "error : Number should be five digits.";
$code= "2";
}

//check if email field is empty
elseif($email == "" ) {
$error= "error : You did not enter a email.";
$code= "3";
} //check for valid email
elseif(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
$error= 'error : You did not enter a valid email.';
$code= "3";
}

else{
echo "Success";
//final code will execute here.
}

}
?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>phpedu108</title>
<style type="text/css">
#mainframe {
margin:auto;
width:600px;
background-color:#fbfbfb;
padding:10px;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333;
background-color: #FFF;
margin: 0px;
}
.error {
border:1px solid #DB4A39 !Important;
}
.message {
color: #DB4A39;
font-weight:bold;
}
.table {
background-color:#EBEBEB;
}
.table td {
background-color:#F8F8F8;
}
.table input[type="text"] {
border-color: #C0C0C0 #D9D9D9 #D9D9D9;
border-radius: 1px 1px 1px 1px;
border-style: solid;
border-width: 1px;
font-family: Verdana, Geneva, sans-serif;
font-size: 14px;
padding: 5px 6px;
width: 185px;
}
.table input[type="text"]:hover {
border-color: #A0A0A0 #B9B9B9 #B9B9B9;
border-style: solid;
border-width: 1px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) inset;
}
.table input[type="Submit"] {
-moz-user-select: none;
background-color: #519A33;
border-color: #3B6E22 #3B6E22 #2C5115;
border-style: solid;
border-width: 1px;
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.1);
color: #FFFFFF;
cursor: pointer;
font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 12px;
font-weight: 700;
height: 28px;
min-width: 40px;
padding: 0 16px;
text-align: center;
}
.table input[type="Submit"]:hover {
text-decoration: none;
}
.table input[type="Submit"]:active {
background-image: none;
}
h1 {
font-size: 160%;
font-weight: normal;
margin: 0 0 0.2em;
}
</style>
</head>
<body>
<div id="mainframe">
  <h1>Server Side Form Validation Demo</h1>
  <p>More tutorials <a href="www.phpedu108.blogspot.com/">http://www.phpedu108.blogspot.com/</a></p>
  <br>
  <form name= "info" id= "info" method= "post" action= "" >
    <table width= "327" border= "0" align="center" cellpadding= "5" cellspacing= "1" class="table">
      <?php if (isset($error)) { ?>
        <tr>
          <td colspan="2" align="center" ><?php echo "<p class='message'>" .$error. "</p>" ; ?></td>
        </tr>
        <?php } ?>
      <tr>
        <td width= "82" align="right" >Name: </td>
        <td width= "238" ><input name= "name" type= "text" value="<?php if(isset($name)){echo $name;} ?>" <?php if(isset($code) && $code == 1){echo "class=error" ;} ?> ></td>
      </tr>
      <tr>
        <td align="right">Number: </td>
        <td><input name= "number" type= "text" id= "number" value="<?php if(isset($number)){echo $number;} ?>"<?php if(isset($code) && $code == 2){echo "class=error" ;}?> ></td>
      </tr>
      <tr>
        <td align="right"> Email: </td>
        <td><input name= "email" type= "text" id= "email" value="<?php if(isset($email)){echo $email; }?>"<?php if(isset($code) && $code == 3){echo "class=error" ;}?> ></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td><input type= "submit" name= "Submit" value= "Submit" /></td>
      </tr>
    </table>
  </form>
</div>
</body>
</html>

how to rotate a image around circle using javascript

how to rotate a image around circle using javascript



CODE :



<head>

<title>Circle Animation</title>
<script type="text/javascript"> <!--
var win; // Window - used for width and height measurement
var cx, cy, x, y; // center xy, radius xy
var centerOffset = 12;
var orbiterOffset = 64;
var radius = 200;
var centerDiv;
var controlDiv;
var orbiter;
var startAngle = 90; // top of circle
var currentAngle = 90;
var interval = 25; // milliseconds

// --></script>
<style type="text/css">
..style1 {
border-style: solid;
border-width: 0px;
}
</style>
</head>

<body>
<div id="centerDiv" style="position:absolute; font-size:24px;">hello </div>
<img src="b.jpg" id="chutney"
style="position:absolute"/>
<div style="position: absolute; left: 10px; top: 313px; width: 95px; height:
30px; z-index: 2" id="buttons">
<form>
&nbsp;<table class="style1">
<tr>
<td>
<input name="Button1" type="button" value="Start"
onclick="startOrbiter()"/>&nbsp;</td>
<td>
<input name="Button2" type="button" value="Stop"
onclick="stopOrbiter()"/>&nbsp;</td>
</tr>
</table>
</form>
</div>
<script type="text/javascript"> <!--
win = document.getElementsByTagName("body")[0];
var timerID;

cx = win.offsetWidth / 2;
cy = win.parentNode.clientHeight / 2;
x = cx;
y = cy - radius;
centerDiv = document.getElementById("centerDiv");
orbiter = document.getElementById("chutney");
controlDiv = document.getElementById("buttons");

function pixelStyle(i)
{
return i + "px";
}

function getCoords()
{
currentAngle = currentAngle - 1 < 0 ? 359 : currentAngle - 1;
x = cx + radius * Math.cos(currentAngle * Math.PI / 180);
y = cy - radius * Math.sin(currentAngle * Math.PI / 180);
}

function moveOrbiter()
{
getCoords();
orbiter.style.left = pixelStyle(x - orbiterOffset);
orbiter.style.top = pixelStyle(y - orbiterOffset);
}

function startOrbiter()
{
timerID = setInterval("moveOrbiter()", interval);
}

function stopOrbiter()
{
clearInterval(timerID);
}
controlDiv.style.left = pixelStyle(cx - 50);
controlDiv.style.top = pixelStyle(win.parentNode.clientHeight - 50);
centerDiv.style.left = pixelStyle(cx - centerOffset);
centerDiv.style.top = pixelStyle(cy - centerOffset);
orbiter.style.left = pixelStyle(x - orbiterOffset);
orbiter.style.top = pixelStyle(y - orbiterOffset);

// --></script>
</body>

</html>

Sunday, 26 May 2013

php program to find factorial of a number

php program to find factorial of a number


Below given a simple php program with form to find factorial of a given number.

CODE :



<?php
$num=$_REQUEST['a'];
 $fact = 1;
    for($i = 1; $i <= $num ;$i++)
        $fact = $fact * $i;
    $res= $fact;
?>

<form action="" method="post">
<table width="50%" border="1">
  <tr>
    <td colspan="2" align="center">&nbsp;<?php echo $res;?></td>
 
  </tr>
  <tr>
    <td>SELECT NUMBER </td>
    <td><input type="text" name="a" /></td>
  </tr>
  <tr>
    <td colspan="2" align="center"><input type="submit" name="go" value="Submit" /></td>
   
  </tr>
</table>

</form>



php progarm to fibonacci series

php progarm to print fibonacci series

CODE :



<?php


   $n=10;//n-th Fibonacci number


     for($a=1,$b=1,$c=0,$i=0;$i<$n;$i++)

        {
          $c=$a+$b;
          if ($i==0) echo $a.' '.$b.' ';
          $a=$b;
          $b=$c;
          echo $c.' ';
         }

?>

Saturday, 25 May 2013

javascript form validation

Javascript form validation

Easy and simple code of javascript form validation shown below:

Code :


<script type="text/javascript">
function validate()
{
var error="";
var status= true;
var emailpattern = /^[A-Za-z0-9\-\.\_]+\@[A-Za-z0-9\-\.]+\.[a-zA-Z]+$/;
if (document.f1.name.value == "")
{
error += "Please enter your name!!!\n";
status = false;
document.f1.name.focus();
}
if (document.f1.email.value == "")
{
error += "Please enter your email Address\n";
status = false;
document.f1.email.focus();
}

if (document.f1.phone.value == "")
{
error += "Please enter Phone Number\n";
status = false;
document.f1.phone.focus();
}

if (document.f1.pwd.value == "")
{
error += "Please enter Password\n";
status = false;
document.f1.pwd.focus();
}

if (document.f1.cpwd.value == "")
{
error += "Please retype your Password\n";
status = false;
document.f1.cpwd.focus();
}
if (!emailpattern.test(document.f1.email.value))
{
error += "Enter a valid email address \n";
status = false;
document.f1.email.focus();
}



if (status == false)
{
alert(error);
return false;
}
else
{


       return true;
 
}
}

</script>

<html>
<head>
<title>phpedu108 tutorial</title>
</head>
<body>
<h2>This is a Form Validation Demo</h2>
<div>More tutorials <a href="http://phpedu108.blogspot.com" style="color:#0066CC; font-weight:bold">http://phpedu108.blogspot.com</a> </div>
<form action="formValid.html" onSubmit="return validate()" name="f1">
<table>
<tr><td>Name:</td><td><input type="text" name="name"></td></tr>
<tr><td>email:</td><td><input type="text" name="email"></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone"></td></tr>
<tr><td>Password:</td><td><input type="Password" name="pwd"></td></tr>
<tr><td>Confirm Password:</td><td><input type="Password" name="cpwd"></td></tr>
<tr><td><input type="Submit" Value="Submit me!!!"></td></tr>
</table>
</form>
</body>
</html>

combo box using javascript or select state and corrensepondence cities

COMBO BOX OR SELECT STATE AND CORRESEPONDENCE CITIES

Below given simple and easy code to create combo box :

Code :


<script>
function com()
{
   if(document.f1.state.value==1)
   {
   //alert("hello");
   document.getElementById("demo").innerHTML="<select><option>mohali</option><option>jalandhar</option></select>";
   document.f1.state.value.focus();
   return true;
   }

   if(document.f1.state.value==2)
   {
   //alert("hello");
   document.getElementById("demo").innerHTML="<select><option>jaipur</option><option>ajmer</option></select>";
   document.f1.state.value.focus();
   return true;
   }

   if(document.f1.state.value==3)
   {
   //alert("hello");
   document.getElementById("demo").innerHTML="<select><option>lucknow</option><option>aligarh</option></select>";
   document.f1.state.value.focus();
   return true;
   }
}
</script>
<form action="" method="post" name="f1">
<select name="state" onchange="com()">
<option value="">Select State</option>
<option value="1">panjab</option>
<option value="2">rajsthan</option>
<option value="3">up</option>
</select>
<p id="demo"></p>
</form>


Output of above code :







Thursday, 23 May 2013

login and logout script using php

Login and logout script using php

Create database 'user_login'



CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL DEFAULT '0',
  `email` varchar(30) NOT NULL,
  `pwd` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
)



Create page config.php

<?php
$sql=mysql_connect("localhost","root","") or die("connection error");
mysql_select_db("user_login",$sql) or die("database not selected");
?>



Create page login.php


<?php
session_start();
include("config.php");
$id=$_REQUEST['id'];
$pwd=$_REQUEST['pwd'];
if($_REQUEST['login'])
{
   if($id=="" or $pwd=="")
   {
   $res="plz fill id and password";
   }
   else
   {
      $sql=mysql_query("select * from user where email='$id'");
 $data=mysql_fetch_array($sql);
      if($data['email']!=$id)
 {
 $res="please fill valid email addres";
 }
 else
 {
if($data['pwd']!=$pwd)
{
$res="plz fill valid password";
}
else
{
$_SESSION['sid']=$id;
header("location:account.php");
}
 }
   }
}
?>
<form action="" method="post">

<fieldset style="width:300px;">
<legend>Login Form</legend>
<p><?php echo $res;?></p>
<p>User Id : <input type="text" name="id"></p>
<p>Password : <input type="password" name="pwd"></p>
<p><input type="submit" name="login" value="Login"></p>
</fieldset>
</form>




Create account.php



<?php
session_start();
$log=$_REQUEST['log'];
if($log=="logout")
{
unset($_SESSION['sid']);
header("location:login.php");
}
$id=$_SESSION['sid'];
if($id=="")
{
header("location:login.php");
}



?>
<body background="theme/<?php echo $theme;?>">
<table width="100%" border="1" height="100%">
  <tr>
    <td width="16%" height="93">Welcome : <?php echo $id;?></td>
    <td width="84%">
    <p align="right"><a href="account.php?log=logout">LOGOUT</a></p></td>
  </tr>
  <tr>
    <td>
</td>
    <td align="center">&nbsp;


</td>
  </tr>
</table>