This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Friday, 7 June 2013

how to upload many images at once in php

This tutorial tell you how to upload many images at once  in php.

 Just copy the code bellow and save it as "image.php" then open it in your server e.g. localhost.

<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
 {
 $uploaded_images = count($_FILES['file']['name']);

 for ($i = 0; $i < $uploaded_images; $i++)
 {
 if($_FILES["file"]["error"][$i] > 0)
 {
  // if there is error in file uploading
   echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br />";
 }
 else
 {

   // check if file already exit in "images" folder.
   if (file_exists("images/" . $_FILES["file"]["name"][$i]))
   {
    echo $_FILES["file"]["name"][$i] . " already exists. "."<br />";
   }
   else
   { 
    //move_uploaded_file function will upload your image.  if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
    if(move_uploaded_file($_FILES["file"]["tmp_name"][$i], "images/" . $_FILES["file"]["name"][$i]))
    {
     //If you want to stor its name in data base code will go here.
       //file has uploaded successfully, If you want to stor its name in data base. see this link http://b2atutorials.blogspot.com/2012/05/upload-image-into-folder-and-save-its.html
 
     echo $_FILES["file"]["name"][$i] . ' -image uploaded.' .'<br />';
    }
   }
 }
 }
 }
 ?>
<html>
<body>
    <form method="post" enctype="multipart/form-data">
    <input type="file" name="file[]" multiple/>
    <input type="submit" value="submit">
    </form>
</body>
</html>
    

    

how to upload and resize image for thumbnail in php

           

This tutorial tell you how to upload and resize image for thumbnail in php.

Just copy the code bellow and save it as "resize_image.php" then open it in your server e.g. localhost.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
 {
 // By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
 $image = $_FILES["file"]["name"];
 //get the name of the temporary copy of the file stored on the server.
 $uploadedfile = $_FILES['file']['tmp_name'];
 //get the type of the uploaded file.
 $image_type =$_FILES["file"]["type"];
 //imagecreatefrompng — Create a new image from file or URL because we are not sure user inputed file is png or with an other extention therefore we will use if else condition.
 if($image_type=='image/png' || $image_type=='image/x-png')
 {
  $src = imagecreatefrompng($uploadedfile);
 }
 elseif($image_type=='image/gif')
 {
  $src = imagecreatefromgif($uploadedfile);
 }
 elseif($image_type=='image/jpeg' || $image_type=='image/jpg' || $image_type == 'image/pjpeg')
 {
  $src = imagecreatefromjpeg($uploadedfile);
 }
 //getimagesize() this function — Get the size of an image which user inputed. we need orignal size for resizing the image in "imagecopyresampled" function.
 list($width,$height)=getimagesize($uploadedfile);
 //We have get orignal height and width by using list($width,$height)=getimagesize($uploadedfile);
 //Now set your own width and height which you want.
 $new_width=100;
 $new_height=100;
 // Bellow function Create a new true color image so that quality of your image don't change.
 $image_p=imagecreatetruecolor($new_width,$new_height);

 // Turn off alpha blending and set alpha flag // otherwise png's images background color will be black.
    imagealphablending($image_p, false);
    imagesavealpha($image_p, true);
 //Fucntion bellow will resize image
 imagecopyresampled($image_p,$src,0,0,0,0,$new_width,$new_height,$width,$height);

 $filename = "images/". $_FILES['file']['name'];

 if(move_uploaded_file($_FILES["file"]["tmp_name"], $filename))
 {
  if($image_type=='image/png' || $image_type=='image/x-png')
   imagepng($image_p,$filename,9) ;
  else
   imagejpeg($image_p,$filename,100);
  echo 'Image uploaded';
  imagedestroy($image_p);
  //file has uploaded successfully, store its name in data base. see this link http://b2atutorials.blogspot.com/2012/05/upload-image-into-folder-and-save-its.html
 }
 }
?>
<html>
<body>
    <form method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="submit">
    </form>
</body>
</html>
    

 

Tuesday, 4 June 2013

how to store data into database easily and reset the form after successful submission

           

Code below will guide you how to store data into database easily. Save this as "save.php" and open it in your host e.g. localhost.
<?php
 session_start();
 // Assing value about your server to these variables for database connection
 $hostname_connect= "localhost";
 $database_connect= "olympic"; //"olympic" this is database name you may create your own database.
 $username_connect= "root";
 $password_connect= "";
 $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
 @mysql_select_db($database_connect) or die (mysql_error());

//if you submit form data submited will be store in database
 if($_POST)
 {
 $key = mt_rand(); // this mt_rand() function genrates randum key for you
 $username = $_POST['username'];
 $email = $_POST['email'];
 $password = $_POST['password'];
 $passconf = $_POST['passconf'];
 $postal_code = $_POST['postal_code'];

 if($_POST['username']=='' || $_POST['email'] =='' || $_POST['password']=='' || $_POST['passconf']=='' || $_POST['postal_code']=='')
 {
  echo "Please fill all fields";
 }
 else
 {
 // save data info database where i have named table as "user" and this is query syntax INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
  $query = "INSERT INTO `user`(`username`,`email`,`password`,`postal_code`,`key`,`status`)VALUES('$username','$email','$password','$postal_code','$key','InActive')";
  $result=mysql_query($query);
   if(!$result)
   {
   echo "Not Saved.";
   }
   else
   {
    //store message in session this will display after redirection.
   $_SESSION["msg"] = "Data has been saved.";
   // line below will redirect you to "save.php" and your form will be reset/refreshed.
   header( "Location: save.php" );
   exit;
   }
 }
 }
 ?>
 <html>
 <body>
<?php
// if session has been set it will show message and unset session.
if(isset($_SESSION["msg"]))
{
 echo '<p style="color:#0C9; font-weight:bold; text-align:center;">'.$_SESSION["msg"].'</p>';
 unset($_SESSION["msg"]);
}
   
 ?>
 <form id='registeration' action='' method='post' >
 <fieldset >
 <legend>Register</legend>
 <label for='username' >Username*: </label><br/>
 <input type='text' name='username' id='username' value="<?php if(!empty($username)) echo $username ?>" maxlength="50" /><br/>
 <label for='email' >Email Address*:</label><br/>
 <input type='text' name='email' id='email' value="<?php if(!empty($email)) echo $email ?>" maxlength="50" /><br/>
 <label for='password' >Password*:</label><br/>
 <input type='password' name='password' id='password' maxlength="50" /><br/>
 <label for='passconf' >Confirm Password*:</label><br/>
 <input type='password' name='passconf' id='password' maxlength="50" /><br/>
 <label for='postal_code' >Postal Code*:</label><br/>
 <input type='text' name='postal_code' id='postal_code' value="<?php if(!empty($postal_code)) echo $postal_code ?>" maxlength="50" /><br/>
 <input type='submit' name='Submit' value='Submit' />
 </fieldset>
 </form>
 </body>
 </html>

 

    

Friday, 31 May 2013

how to create your own captcha image easily

This tutorial tell you how to create your own captcha image.
You should follow these steps:
  1. Copy the code below and save it as "create_image.php"
    <?php
    //Start the session so we can store what the security code actually is
    session_start();
    //Send a generated image to the browser
    Create_Captcha_Images();
    exit();
    function Create_Captcha_Images() {
    $width='135';
    $height='30';
    //Let's generate a totally random string using md5
    $md5_hash = md5(rand(0,999));
    //We don't need a 32 character long string so we trim it down to 5
    $code = substr($md5_hash, 15, 5);
    //Set the session to store the security code
    $_SESSION["security_code"] = $code;
    //create image resource using width and height
    $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
    /* set the colours */
    $background_color = imagecolorallocate($image, 255, 255, 255);
    $text_color = imagecolorallocate($image, 0, 0, 0);
    $noise_color = imagecolorallocate($image, 100, 120, 180);
    /* generate random dots in background */
    for( $i=0; $i<110; $i++ ) {
    imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
    }
    /* generate random lines in background */
    for( $i=0; $i<250; $i++ ) {
    imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
    }
    // add white string to box with params: image, font (1-5), x, y, string and color
    imagestring($image, 5, 40, 7, $code, $text_color);
    /* output captcha image to browser */
    header('Content-Type: image/jpeg');
    imagejpeg($image);
    imagedestroy($image);

    }
    ?>
  2. Copy the code below and save it as "contact_us.php".
    <?php
    session_start();
    if(isset($_POST['submit']))
    {
    $image = $_POST['antibot_input_str'];
    if($image == $_SESSION["security_code"])
    {
    echo 'Your Entered code has matched go ahead. e.g. store your form data into database';
    }
    else
    {
    $mail_sent = 'Your Entered code does not match';
    }
    }
    ?>
    <!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>Untitled Document</title>
    </head>
    <body>
    <form method="post" action="contact_us.php">
    <table align="center">
    <tr valign="middle">
    <td class="FormButton">First name</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap">
    <input type="text" value="" maxlength="32" size="32" name="firstname" id="firstname">
    </td>
    </tr>
    <tr valign="middle">
    <td class="FormButton">Last name</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap">
    <input type="text" value="" maxlength="32" size="32" name="lastname" id="lastname">
    </td>
    </tr>
    <tr>
    <td class="iv-box-descr" colspan="3">Type the characters you see in the picture. (If you do not see any picture here, please enable images in your web browser options and refresh this page):</td>
    </tr>
    <tr>
    <td class="iv-box" colspan="2">
    <div class="iv-img">
    <img id="imgCaptcha" src="create_image.php"/><br>
    <a onclick="
    document.getElementById('imgCaptcha').src = 'create_image.php?' + Math.random();
    return false;
    " href="javascript:void(0);">Get a different code</a>
    </div>
    <br> </td>
    <td class="iv-box">
    <input type="text" name="antibot_input_str">
    </td>
    </tr>
    <tr valign="middle">
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>
    <input id="insert" name="submit" type="submit" value="Submit" />
    </td>
    </tr>
    </table>
    </form>
    </body>
    </html>

Wednesday, 29 May 2013

How to change states list depending on selected country

This tutorial tell you how to How to change states list depending on selected country.
You should follow these steps:
  1. Create your database connection.e.g.
    <?php
    $con=mysql_connect ("localhost","username","password");
    @mysql_select_db('your_bd') or die(mysql_error());
    // Check connection
    if (!$con)
    {
    echo "Failed to connect to MySQL: ";
    }

    ?>
  2. Create states and country tables.
    CREATE TABLE IF NOT EXISTS `states` ( `stateid` int(11) NOT NULL AUTO_INCREMENT, `state` varchar(32) NOT NULL DEFAULT '', `code` varchar(32) NOT NULL DEFAULT '', `country_code` char(2) NOT NULL DEFAULT '', PRIMARY KEY (`stateid`), UNIQUE KEY `code` (`country_code`,`code`), KEY `state` (`state`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=186 ;

    CREATE TABLE IF NOT EXISTS `country` ( `country_code` char(2) NOT NULL default '', `country_name` varchar(90) NOT NULL default '' ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  3. Insert values in tables.
    INSERT INTO `country` (`country_code`, `country_name`) VALUES ('GB', 'United Kingdom (Great Britain)'), ('US', 'United States'), ('PK', 'Pakistan');

    INSERT INTO `states` (`stateid`, `state`, `code`, `country_code`) VALUES (1, 'Aberdeenshire', 'ABd', 'GB'), (2, 'Angus', 'AG', 'GB'), (3, 'Argyll', 'ARg', 'GB'), (4, 'Avon', 'AV', 'GB'), (5, 'Ayrshire', 'AY', 'GB'), (6, 'Alabama', 'AL', 'US'), (7, 'Alaska', 'AK', 'US'), (8, 'Arizona', 'AZ', 'US'), (9, 'Arkansas', 'AR', 'US'), (10, 'California', 'CA', 'US');
  4. Copy code below and create a file named "get_state.php"
    <?php
    // Copy this code and create a file named get_state.php
    include_once('db_connection.php');
    $code = $_GET['code'];
    $result = mysql_query("SELECT * FROM `states` WHERE country_code = '".$code."'");
    if(mysql_num_rows($result) > 0)
    {
    echo '<select name="b_state" id="b_state" style="width:220px;">';
    while($row = mysql_fetch_array($result))
    {
    echo "<option value=".$row['code'].">".$row['state']."</option>";
    }
    echo '</select>';
    }
    else
    {
    echo '<input type="text" size="32" value="" name="b_state" id="b_state">';
    }
    ?>
  5. Copy and past code below and save it as "states.php".
    <?php
    // include your database connection.
    include_once('db_connection.php');
    // // create tables
    ?>
    <!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>
    <!--don't forget to include jquery-->
    <script src="js/jquery.js"></script>
    <script type="text/javascript">
    function change_state(state)
    {
    // Below is post ajax request which goes to "get_state.php" where state list changes on the base of parameter "code" which is set by user on_change event.
    // then result is passed to '#state_container' id of <td> which is parent of <select> element.
    $.post('get_state.php?code='+state, function(data) {
    $('#state_container').html(data);
    });
    }
    </script>
    </head>
    <body>
    <table width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-bottom:5px;">
    <tbody>
    <tr>
    <td></td>
    <td style="padding-top:15px;">
    <form name="registerform" id="insertform" method="post" action="contact_us.php">
    <table width="100%" cellspacing="0" cellpadding="2">
    <tbody>
    <tr valign="middle">
    <td class="FormButton">County/State</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap" id="state_container">

    <?php
    // Below if else condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_country']))
    $code = $_POST['b_country']; //IF contry selected show states of that country else show states of UK.
    else
    $code = 'GB';
    ////// Query below show the states on the base of country_code.
    $result = mysql_query("SELECT * FROM `states` WHERE country_code = '".$code."'");
    if(mysql_num_rows($result) > 0)
    {
    // IF states exit in database show dropdown else show input text field so that user can enter state manually.
    echo '<select name="b_state" id="b_state" style="width:220px;">';
    while($row = mysql_fetch_array($result))
    {
    // Below if condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_state']))
    echo $selected = ($row['code']==$_POST['b_state']) ? "selected='selected'" : "";
    echo "<option ".$selected." value=".$row['code'].">".$row['state']."</option>";
    }
    echo '</select>';
    }
    else
    {
    // Below if else condition is for the purpose of saving the users selected value if validation error occur.
    if(isset($_POST['b_state']))
    $value = $_POST['b_state'];
    else
    $value = '';
    echo '<input type="text" size="32" value="'.$value.'" name="b_state" id="b_state">';
    }
    ?>

    </td>
    </tr>

    <tr valign="middle">
    <td class="FormButton">Country</td>
    <td><font class="Star">*</font></td>
    <td nowrap="nowrap">
    <!-- Below onchange event calls the change_state() with value of selected Country code-->
    <select onchange="javascript: change_state(this.value);" name="b_country" id="b_country" style="width:220px;">
    <?php
    // Query below showes the list of `countries`.
    $result = mysql_query("SELECT * FROM `country`");
    if(mysql_num_rows($result) > 0)
    {
    while($row = mysql_fetch_array($result))
    {
    // Below if else condition is for the purpose of saving the users selected value if validation error occurs.
    if(isset($b_country))
    $selected = ($row['country_code']==$b_country) ? "selected='selected'" : "";
    else // This is for first time uk will be selected by default.
    $selected = ($row['country_code']=='GB') ? "selected='selected'" : "";

    echo "<option ".$selected." value=".$row['country_code'].">".$row['country_name']."</option>";
    }
    }
    ?>
    </select>
    </td>
    </tr>
    </tbody></table>
    </form>
    </body>
    </html>

How to display images stored in database

           

This code is for showing your images from database. (Don't forget to connect with dababase).
You can see storage of images in database here.

<?php
 $query_image = "SELECT * FROM acc_images";
 // This query will show you all images if you want to see only one image pass acc_id='$id' e.g. ""SELECT * FROM acc_images WHERE acc_id='$id'".
 $result = mysql_query($query_image);
 if(mysql_num_rows($result) > 0)
 {
   while($row = mysql_fetch_array($result))
   {
  echo '<img alt="" src="images/'.$row["image"].'">';
   }
 }
 else
 {
  echo 'File name not found in database';
 }
?>

 

Monday, 17 September 2012

csv export and import script using php

Code bellow will be helpfull for you for importing and exporting csv files. Copy the code bellow and save it as "import_export_csv.php" then open it in your host e.g. 'localhost' and start importing, exporting csv files.

<?php
//don't forget to include your database connectivity.
 include('db_connection.php');
 if ($REQUEST_METHOD=="POST" && $_POST['btnSubmit']== 'Export') //this code is for exporting data when you click on "Export" this part of code will be executed.
 {
   // if you want to export data from a database table. You have to give your_table name in bellow query.
   $select = "SELECT * FROM Your_table";
   $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
// code bellow will get names of the fields and set as header of the csv.
   $fields = mysql_num_fields ( $export );
   for ( $i = 0; $i < $fields; $i++ )
   {
    $header .= '"'.mysql_field_name( $export , $i ).'"';
    if($i != $fields-1)
    $header .= ",";
   }
//if data found in database arrange it in csv format and pass to a variable $data.
   while( $row = mysql_fetch_row( $export ) )
   {
    $line = '';
    foreach( $row as $value )
    {                                           
     if ( ( !isset( $value ) ) || ( $value == "" ) )
     {
      $value = '"'."\t".'",';
     }
     else
     {
      $value = str_replace( '"' , '""' , $value );
      $value = '"' . $value . '"' . ",";
     }
     $line .= $value;
    }
 
    $line = substr($line, 0, -1);
    $data .= trim( $line ) . "\n";
   }
   $data = str_replace( "\r" , "" , $data );
//if data=='' not found in database
   if ( $data == "" )
   {
    $data = "\n(0) Records Found!\n";                       
   }
   header("Content-type: application/octet-stream");
   header("Content-Disposition: attachment; filename=products_csv.csv");
   header("Pragma: no-cache");
   header("Expires: 0");
// display fields name and data here
   print "$header\n$data";
   exit;
 }
 elseif ($REQUEST_METHOD=="POST" && $_POST['btnSubmit']== 'Import') //this code is for importing data when you click on "Import" this part of code will be executed.
 {
 
   if ($_FILES[csv][size] > 0)
   {
    //get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file, "r");
    $row=1;
 //fgetcsv — Gets line from file pointer and parse for CSV fields
    while (($line_of_data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
  //If your first line from csv contains fields names ignore it.
     if($row!=1)
     {
      // $line_of_data is numaric array has your impoted data $line_of_data[0] has your first record from csv which is fields name normaly.
      $query = "insert into yourtable (username, email) values ('$line_of_data[0]', '$line_of_data[1]')";
      mysql_query ($query) or die ( "Sql error : " . mysql_error( ) );
   
     }
      $row++;
        }
    echo "File imported successfuly.";
 
   }
 }
 ?>
 <div style="margin:0 auto; width:100%">
 <form method="post" name="form1" action="import_export_csv.php">
 click here for export a csv file: <input type="submit" name="btnSubmit" value="Export" />
 </form>
 </div>
 <div style="margin:10px auto; width:100%">
 <form method="post" name="form2" enctype="multipart/form-data" action="import_export_csv.php">
 select your .csv file: <input type="file" name="csv" />
 <input type="submit" name="btnSubmit" value="Import" />
 </form>
 </div>    

    

using google map lookup address by postal code

       

   <?php
    // First, we need to take their postcode and get the lat/lng pair:
    $postcode = 'SL1 2PH';
    // Sanitize their postcode:
    $search_code = urlencode($postcode);
    $url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $search_code . '&sensor=false';
 //json_decode() returns an object pass 2nd parameter true to json_decode() if you want to get results as array
    $json = json_decode(file_get_contents($url), true);
 //print_r($json);  uncomment for seeing whole arry
     $lat = $json['results'][0]['geometry']['location']['lat'];
     $lng = $json['results'][0]['geometry']['location']['lng'];
    // Now build the lookup:
    $address_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&sensor=false';
 //json_decode() returns an object if you want to get results as array, pass 2nd parameter true e.g. json_decode(file_get_contents($address_url, true))
    $address_json = json_decode(file_get_contents($address_url), true);
    print_r($address_json['results'][0]['formatted_address']);
 ?>    

    

Monday, 14 May 2012

How to write a php script for file downloading

In this tutorials you will learn how to write a php script for file downloading.If you want to see how to upload a file into a server click here.

<?php 
// Give the path here where your file is located and make a hyper link like <a href='www.yoursite.com?fname=youpic.jpg'>Download image</a>
//$_GET['fname']; will get the file name you given in hyper link and start downloading

$file = 'admin/upload/'.$_GET['fname'];
header("Expires: 0"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: no-store, no-cache, must-revalidate"); 
header("Cache-Control: post-check=0, pre-check=0", false); 
header("Pragma: no-cache"); 
header("Content-type: application/pdf");   
header('Content-length: '.filesize($file)); 
header('Content-disposition: attachment; filename='.basename($file)); 
readfile($file); 
// Exit script. So that no useless data is output-ed. 
exit; 
?> 

 

Wednesday, 9 May 2012

Upload image into folder and save its name into database

This tutorial tell you how to Upload image into folder and save its name into database.
You should follow these two steps:
  1. Creat a database named 'olympic' and a table named 'acc_images'.
    CREATE TABLE IF NOT EXISTS `acc_images` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `acc_id` int(11) unsigned NOT NULL, `image` varchar(255) NOT NULL, `status` varchar(20) NOT NULL, PRIMARY KEY (`id`), );
  2. Copy and past code given below.
    <?php
    // Assigning value about your server to variables for database connection
    $hostname_connect= "localhost";
    $database_connect= "olympic";
    $username_connect= "root";
    $password_connect= "";
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    if($_POST)
    {
    // $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.

    if ($_FILES["file"]["error"] > 0)
    {
    // if there is error in file uploading
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    }
    else
    {
    // check if file already exit in "images" folder.
    if (file_exists("images/" . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {  //move_uploaded_file function will upload your image.  if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
    if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))
    {
    // If file has uploaded successfully, store its name in data base
    $query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
    if(mysql_query($query_image))
    {
    echo "Stored in: " . "images/" . $_FILES["file"]["name"];
    }
    else
    {
    echo 'File name not stored in database';
    }
    }
    }


    }
    }
    ?>
    <html>
    <body>
    <form action="" method="post"enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <br />
    <input type="submit" name="submit" value="Submit" />
    </form>
    </body>
    </html>

Tuesday, 8 May 2012

Create a comma separated csv from sql query


<?php
$select = "SELECT * FROM Your_table";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
    $header .= '"'.mysql_field_name( $export , $i ).'"';
 if($i != $fields-1)
 $header .= ",";
}
while( $row = mysql_fetch_row( $export ) )
{

    if(isset($row[0]) && $row[0] != ''){
  $row[0] = text_decrypt($row[0]);
 }
 $line = '';
    foreach( $row as $value )
    {                                           
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . ",";
        }
        $line .= $value;
    }

 $line = substr($line, 0, -1);
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                       
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_file_name.csv");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>

Sunday, 6 May 2012

Make a Sign in form and store data in session

This tutorial tell you how to match username and password entered by user with stored records in database. Then store username in session variable. You can see sing up form here
You should follow these two points:
  1. Creat a database named 'olympic' and a table named 'user'.
    CREATE TABLE IF NOT EXISTS `user` ( `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `postal_code` int(11) NOT NULL, `status` varchar(20) NOT NULL, `key` varchar(20) NOT NULL, `id` int(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
  2. Copy and past code given below.
    <?php
    // Assigning value about your server to variables for database connection
    $hostname_connect= "localhost";
    $database_connect= "olympic";
    $username_connect= "root";
    $password_connect= "";
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    if($_POST)
    {
    $username=$_POST['username'];
    $password=$_POST['password'];

    $user_query="select * from user where username='$username'and password='$password'";

    $user_result=mysql_query($user_query);
    $user_row=mysql_fetch_array($user_result);
    $id=$user_row['id'];
    $num_user=mysql_num_rows($user_result);
    // Above query matches username and password entered by user with database records.
    if($num_user==1)
    {
    // if username and password exist in database assign username to session.
    // echo $_SESSION['username'] where you want to display username to user in you website
    $_SESSION['username'] = $user_row['username'];
    $_SESSION['id']=$id;
    // redirect user to home page or where you want
    header('Location: index.php');
    }
    else
    {
    echo "Invalid User Name or Password";
    }
    }
    ?>


    <form id='register' action='' method='post'>
    <fieldset >
    <legend>Register</legend>
    <input type='hidden' name='submitted' id='submitted' value='1'/>
    <label for='username' >Username*: </label><br/>
    <input type='text' name='username' id='username' value="<?php if(!empty($username)) echo $username ?>" maxlength="50" /><br/>
    <label for='Password' >Password*:</label><br/>
    <input type='password' name='password' id='password' maxlength="50" /><br/>
    <input type='submit' name='Submit' value='Submit' />
    </fieldset>
    </form>

How to save form data in database and send activation key

In this tutorial you will learn how to save signup form data in database and send activation key to user's email. I am not including validation code here if you want to validate your form submission code click here to see. For looking the sign in form click here
You should follow these two points:
  1. Creat a database named 'olympic' and a table named 'user'.
    CREATE TABLE IF NOT EXISTS `user` ( `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `postal_code` int(11) NOT NULL, `status` varchar(20) NOT NULL, `key` varchar(20) NOT NULL, `id` int(11) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
  2. Copy and past code given below.
    <?php
    // Assing value about your server to these variables for database connection
    $hostname_connect= "localhost";
    $database_connect= "olympic";
    $username_connect= "root";
    $password_connect= "";
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    if($_POST)
    {
    $key = mt_rand(); // this mt_rand() function genrates randum key for you
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $passconf = $_POST['passconf'];
    $postal_code = $_POST['postal_code'];

    // code below checks username in database exist or not. if exist data will not submit to database
    $user_query="select username from user where username='$username'";

    $user_result=mysql_query($user_query);
    $user_row=mysql_fetch_array($user_result);
    if(!empty($user_row))
    {
    if($user_row['username'])
    {
    echo 'Username Already exist';
    }


    }
    else
    {
    //If username not already exist then insert data into 'user' table
    $q = "INSERT INTO `user`(`username`,`email`,`password`,`postal_code`,`key`,`status`)VALUES('$username','$email','$password','$postal_code','$key','InActive')";

    $qr=mysql_query($q);
    if(!$qr){
    echo "Not Submitted";
    }
    else
    {
    // if data has saved in data base then code below will send email to user
    $to = $email;
    $subject = "Activation key";
    $message = "Your activation key is this" .$key.'<br>'.' click here to activate your acount.<a href="localhost">here</a>';
    $from = "admin_abc@yahoo.com";
    $headers = "From:" . $from;
    if(mail($to,$subject,$message,$headers))
    {
    echo "Check your email to activate your acount.";
    }
    else
    {
    echo "Email not sended";
    // if you are working on localhost email will not send and below line helps you to activates your acount
    echo $message = "Your activation key is this " .$key.'<br>'.' click here to activate your acount. <a href="activation.php?key='.$key.'">here</a>';
    }
    }
    }
    }
    ?>
    <html>
    <body>
    <form id='registeration' action='' method='post' >
    <fieldset >
    <legend>Register</legend>
    <input type='hidden' name='submitted' id='submitted' value='1'/>
    <label for='username' >Username*: </label><br/>
    <input type='text' name='username' id='username' value="<?php if(!empty($username)) echo $username ?>" maxlength="50" /><br/>
    <label for='email' >Email Address*:</label><br/>
    <input type='text' name='email' id='email' value="<?php if(!empty($email)) echo $email ?>" maxlength="50" /><br/>
    <label for='password' >Password*:</label><br/>
    <input type='password' name='password' id='password' maxlength="50" /><br/>
    <label for='passconf' >Confirm Password*:</label><br/>
    <input type='password' name='passconf' id='password' maxlength="50" /><br/>
    <label for='postal_code' >Postal Code*:</label><br/>
    <input type='text' name='postal_code' id='postal_code' value="<?php if(!empty($postal_code)) echo $postal_code ?>" maxlength="50" /><br/>
    <input type='submit' name='Submit' value='Submit' />
    </fieldset>
    </form>
    </body>
    </html>

Sunday, 15 April 2012

PHP Validation for complete SignUp form

For PHP validation I am using the same regular expression rules as I have used and described in detail during java script validation for complete signup form. Below is complete PHP validation code. Copy and paste it in your text editor and save it with PHP extension (e.g. validation.php). Then open it in localhost server you will see it working well.
Code bellow has two parts:
  1. HTML which contains html form which you can see on your browser
  2. PHP which get user data using the globle variable $_POST and validates it using the regular expression
<?php
if($_POST['submit'] == 'Submit')
{
//If user click on submit button we get value by using $_POST where names in sequre brackets are the names of form's input fields.
$username = $_POST['username'];
$email = $_POST['email'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$passconf = $_POST['passconf'];

// Now you check if $username is empty you assign coresponding error message to an associative array named $error. You can display error message for your user using this array in HTML part.
if($username=='')
{
$error['username']= 'Please enter username <br>';
}

else if(!ereg("^[a-zA-Z0-9_]{3,16}$", $username))
{
// else codition checks if username not contains alpha-numeric characters and it is less than 3 characters or more than 16 characters. It assign error message to $error array. Validate similaely other data email, phone etc.
$error['username']= 'please enter valid username<br>';

}

if($email=='')
{
$error['email']= 'Please enter email <br>';
}
else if(!ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $email))
{
$error['email']= 'please enter valid email<br>';
}

if($password=='')
{
$error['password']= 'Please enter password<br>';
}
else if(strlen($password)<6)
{
$error['password']= 'Password is too short.<br>';
}
if($passconf=='')
{
$error['passconf']= 'Please confirm password<br>';
}
else if($password!=$passconf)
{
$error['passconf']= 'password does not match<br>';
}

if($firstname=='')
{
$error['firstname']= 'Please enter firstname<br>';
}
else if(!ereg("^[a-zA-Z]{3,16}$", $firstname))
{
$error['firstname']= 'please enter valid firstname<br>';
}
if($lastname=='')
{
$error['lastname']= 'Please enter lastname<br>';
}
else if(!ereg("^[a-zA-Z]{3,16}$", $lastname))
{
$error['lastname']= 'please enter valid lastname<br>';
}
if($phone=='')
{
$error['phone']= 'Please enter phone<br>';
}
else if(!ereg("^[0-9]{3,16}$", $phone))
{
$error['phone']= 'please enter valid phone<br>';
}
 //if error not exist store data into database or send to email server.
 if(count($error)==0)
 {
  // You can see following links for storing data into database.
  // http://b2atutorials.blogspot.com/2012/05/how-to-save-sign-up-form-data-in.html
  // http://b2atutorials.blogspot.com/2013/06/how-to-store-data-into-database-easily.html
 }
}
?>
<html>
<body>
<form name="signup" action="" method="post">
<ul>
<li>
<p>Username:</p>
<p><?php
//Now check if $error['username'] is not empty display the error message you have assign it above.
if(!empty($error['username'])) echo $error['username']; ?></p>
<p><input type="text" name="username" value="<?php if(!empty($username)) echo $username ?>" size="50" /></p>
</li>
<li>
<p>Email:</p>
<p><?php if(!empty($error['email'])) echo $error['email']; ?></p>
<p><input type="text" name="email" value="<?php if(!empty($email)) echo $email ?>" size="50" /></p></li>
<li><p>Password:</p>
<p><?php if(!empty($error['password'])) echo $error['password']; ?></p>
<p><input type="password" name="password" value="<?php if(!empty($password)) echo $password ?>" size="50" /></p></li>
<li>
<p>Password Confirm:</p>
<p><?php if(!empty($error['passconf'])) echo $error['passconf']; ?></p>
<p><input type="password" name="passconf" value="<?php if(!empty($passconf)) echo $passconf ?>" size="50" /></p></li>
<li>
<p>First Name:</p>
<p><?php if(!empty($error['firstname'])) echo $error['firstname']; ?></p>
<p><input type="text" name="firstname" value="<?php if(!empty($firstname)) echo $firstname ?>" size="50" /></p></li>
<li>
<p>Last Name:</p>
<p><?php if(!empty($error['lastname'])) echo $error['lastname']; ?></p>
<p><input type="text" name="lastname" value="<?php if(!empty($lastname)) echo $lastname ?>" size="50" /></p></li>
<li>
<p>Phone:</p>
<p><?php if(!empty($error['phone'])) echo $error['phone']; ?></p>
<p><input type="text" name="phone" value="<?php if(!empty($phone)) echo $phone ?>" size="50" /></p></li>
<li>
<p><input type="submit" name="submit" value="Submit" /></p>
</li></ul>
</form>
</body>
</html>