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

One Page Template Scrolling Script

One Page Template Scrolling Script


Hi Today discussed Bootstrap template one page template Scrollig Script url passing id and the scroll script.Follow us script.

One Page Template Scrolling Script
One Page Template Scrolling Script


JavaScript

<script type="text/javascript">
!function(t){"use strict";t("a.page-scroll").bind("click",function(a){var o=t(this);t("html, body").stop().animate({scrollTop:t(o.attr("href")).offset().top-50},1250,"easeInOutExpo"),a.preventDefault()}),t("body").scrollspy({target:".navbar-fixed-top",offset:51}),t(".navbar-collapse ul li a").click(function(){t(".navbar-toggle:visible").click()}),t("#mainNav").affix({offset:{top:100}})}(jQuery);
</script>

How to Import and Export CSV Files Using PHP and MySQL

How to Import and Export CSV Files Using PHP and MySQL


Hi Today discussed PHP Server side Scripting Language How to Import and Export CSV Files using PHP and mysql. Database normally insert and update and delete queries and bulk insert it's means csv file same column file data csv file data insert mysql. code follows.


How to Import and Export CSV Files Using PHP and MySQL
How to Import and Export CSV Files Using PHP and MySQL



First Create database and then create table.

CREATE DATABASE employee
Create table

CREATE TABLE employeedetils(
eid VARCHAR(50) UNSIGNED PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
create_date VARCHAR(50)
)
dbconnect

<?php
function getdb(){
$servername = "localhost";
$username = "root";
$password = "";
$db = "employee";

try {
   
    $conn = mysqli_connect($servername, $username, $password, $db);
     //echo "Connected successfully"; 
    }
catch(exception $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
    return $conn;
}
?>
PHP File Import function phpfiles.php

<?php


 if(isset($_POST["Import"])){
  
  $filename=$_FILES["file"]["tmp_name"];  


   if($_FILES["file"]["size"] > 0)
   {
     $file = fopen($filename, "r");
         while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
          {


            $sql = "INSERT into employeedetils(eid,firstname,lastname,email,create_date)                    values ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[3]."','".$getData[4]."')";
                   $result = mysqli_query($con, $sql);
    if(!isset($result))
    {
     echo "<script type=\"text/javascript\">
       alert(\"Invalid File:Please Upload CSV File.\");
       window.location = \"index.php\"
        </script>";  
    }
    else {
       echo "<script type=\"text/javascript\">
      alert(\"CSV File has been successfully Imported.\");
      window.location = \"index.php\"
     </script>";
    }
          }
   
          fclose($file); 
   }
 }  


 ?>

View Page design bootstrap lib include

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
View Page


<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>

</head>

<body>
    <div id="wrap">
        <div class="container">
            <div class="row">

                <form class="form-horizontal" action="phpfiles.php" method="post" name="upload_excel" enctype="multipart/form-data">
                    <fieldset>

                        <!-- Form Name -->
                        <legend>Form Name</legend>

                        <!-- File Button -->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="filebutton">Select File</label>
                            <div class="col-md-4">
                                <input type="file" name="file" id="file" class="input-large">
                            </div>
                        </div>

                        <!-- Button -->
                        <div class="form-group">
                            <label class="col-md-4 control-label" for="singlebutton">Import data</label>
                            <div class="col-md-4">
                                <button type="submit" id="submit" name="Import" class="btn btn-primary button-loading" data-loading-text="Loading...">Import</button>
                            </div>
                        </div>

                    </fieldset>
                </form>

            </div>
            <?php
               getdbrecords();
            ?>
        </div>
    </div>
</body>

</html>
view php records

function getdbrecords(){
    $con = getdb();
    $Sql = "SELECT * FROM employeedetils";
    $result = mysqli_query($con, $Sql);  


    if (mysqli_num_rows($result) > 0) {
     echo "<div class='table-responsive'><table id='myTable' class='table table-striped table-bordered'>
             <thead><tr><th>EMP ID</th>
                          <th>First Name</th>
                          <th>Last Name</th>
                          <th>Email</th>
                          <th>Registration Date</th>
                        </tr></thead><tbody>";


     while($row = mysqli_fetch_assoc($result)) {

         echo "<tr><td>" . $row['eid']."</td>
                   <td>" . $row['firstname']."</td>
                   <td>" . $row['lastname']."</td>
                   <td>" . $row['email']."</td>
                   <td>" . $row['create_date']."</td></tr>";        
     }
    
     echo "</tbody></table></div>";
     
} else {
     echo "you have no records";
}
}

Export MySQL to CSV With PHP

<div>
            <form class="form-horizontal" action="phpfiles.php" method="post" name="upload_excel"   
                      enctype="multipart/form-data">
                  <div class="form-group">
                            <div class="col-md-4 col-md-offset-4">
                                <input type="submit" name="Export" class="btn btn-success" value="export to excel"/>
                            </div>
                   </div>                    
            </form>           
 </div>
Export Functions

if(isset($_POST["Export"])){
   
      header('Content-Type: text/csv; charset=utf-8');  
      header('Content-Disposition: attachment; filename=data.csv');  
      $output = fopen("php://output", "w");  
      fputcsv($output, array('ID', 'First Name', 'Last Name', 'Email', 'Joining Date'));  
      $query = "SELECT * from employeedetils ORDER BY emp_id DESC";  
      $result = mysqli_query($con, $query);  
      while($row = mysqli_fetch_assoc($result))  
      {  
           fputcsv($output, $row);  
      }  
      fclose($output);  
 }  

Ionic Framework Paypal Payment Gateway

Ionic Framework Paypal Payment Gateway


Today Discussed Ionic Framework Paypal payment Gateway. First  Ionic Framework Cordova Plugin. and How to get payment gateway integrated follows. 
Ionic Framework Paypal Payment Gateway
Ionic Framework Paypal Payment Gateway
IK have developed a mobile app using ionic framework and cordova. In my backend mysql. and storing data using php code. Cordova Plugin ClientID here  api keys.

 $scope.buyNow = function ()
    {
        PaypalService.initPaymentUI().then(function () { PaypalService.makePayment(50, "Total").then();       });
    }
PaypalService is implemented as 
ngular.module('starter.PaypalService', ['starter.Constants'])
.factory('PaypalService', ['$q', '$ionicPlatform','Constants', '$filter', '$timeout', function ($q, $ionicPlatform, Constants, $filter, $timeout) {



    var init_defer;
    /**
     * Service object
     * @type object
     */
    var service = {
        initPaymentUI: initPaymentUI,
        createPayment: createPayment,
        configuration: configuration,
        onPayPalMobileInit: onPayPalMobileInit,
        makePayment: makePayment
    };


    /**
     * @ngdoc method
     * @name initPaymentUI
     * @methodOf app.PaypalService
     * @description
     * Inits the payapl ui with certain envs.
     *
     *
     * @returns {object} Promise paypal ui init done
     */
    function initPaymentUI() {

        init_defer = $q.defer();
        $ionicPlatform.ready().then(function () {

            var clientIDs = {
                "PayPalEnvironmentProduction": Constants.payPalProductionId,
                "PayPalEnvironmentSandbox": Constants.payPalSandboxId
            };
            PayPalMobile.init(clientIDs, onPayPalMobileInit);
        });

        return init_defer.promise;
    }

    /**
     * @ngdoc method
     * @name createPayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Creates a paypal payment object
     *
     *
     * @returns {object} PayPalPaymentObject
     */
    function createPayment(total, name) {

        // "Sale  == >  immediate payment
        // "Auth" for payment authorization only, to be captured separately at a later time.
        // "Order" for taking an order, with authorization and capture to be done separately at a later time.
        var payment = new PayPalPayment("" + total, "INR", "" + name, "Sale");
        return payment;
    }
    /**
     * @ngdoc method
     * @name configuration
     * @methodOf app.PaypalService
     * @description
     * Helper to create a paypal configuration object
     *
     *
     * @returns {object} PayPal configuration
     */
    function configuration() {
        // for more options see `paypal-mobile-js-helper.js`
        var config = new PayPalConfiguration({merchantName: Constants.payPalShopName, merchantPrivacyPolicyURL: Constants.payPalMerchantPrivacyPolicyURL, merchantUserAgreementURL: Constants.payPalMerchantUserAgreementURL});
        return config;
    }

    function onPayPalMobileInit() {
        $ionicPlatform.ready().then(function () {
            // must be called
            // use PayPalEnvironmentNoNetwork mode to get look and feel of the flow
            PayPalMobile.prepareToRender(Constants.payPalEnv, configuration(), function () {

                $timeout(function () {
                    init_defer.resolve();
                });

            });
        });
    }
    /**
     * @ngdoc method
     * @name makePayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Performs a paypal single payment
     *
     *
     * @returns {object} Promise gets resolved on successful payment, rejected on error
     */
    function makePayment(total, name) {


        var defer = $q.defer();
        total = $filter('number')(total, 2);
        $ionicPlatform.ready().then(function () {
            PayPalMobile.renderSinglePaymentUI(createPayment(total, name), function (result) {
                $timeout(function () {
                    defer.resolve(result);
                });
            }, function (error) {
                $timeout(function () {
                    defer.reject(error);
                });
            });
        });

        return defer.promise;
    }

    return service;
}]);
Followed Step

API Backend and Integrations

Every app talks to a server or backed and Appery.io provides a complete backend for your app:

  • Database - for storing app data.
  • Server Code - for writing app logic on the server using JavaScript.
  • API Express - exposing enterprise data sources such as an SQL database or SOAP service via REST APIs. Also, build advanced services with a visual service editor.
  • Push Notifications - send Push Notifications to your users.

Crop Image in Core PHP

Crop Image in Core PHP

Today Discussed Crop Image in Core PHP. Image crop and create thumb image and upload save particular directory. crop this image and resize compressed image save a directory. code follow us. 
Crop Image in Core PHP
Crop Image in Core PHP
$upload_dir = "upload_pic";     // The directory for the images to be saved in
$upload_path = $upload_dir."/";    // The path to where the image will be saved
$large_image_prefix = "resize_";    // The prefix name to large image
$thumb_image_prefix = "thumbnail_";   // The prefix name to the thumb image
$large_image_name = $large_image_prefix.$_SESSION['random_key'];     // New name of the large image (append the timestamp to the filename)
$thumb_image_name = $thumb_image_prefix.$_SESSION['random_key'];     // New name of the thumbnail image (append the timestamp to the filename)
$max_file = "3";        // Maximum file size in MB
$max_width = "500";       // Max width allowed for the large image
$thumb_width = "100";      // Width of thumbnail image
$thumb_height = "100";      // Height of thumbnail image
// Only one of these image types should be allowed for upload
$allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
$allowed_image_ext = array_unique($allowed_image_types); // do not change this
$image_ext = ""; // initialise variable, do not change this.
foreach ($allowed_image_ext as $mime_type => $ext) {
    $image_ext.= strtoupper($ext)." ";
}

Image Resize Function


function resizeImage($image,$width,$height,$scale) {
 list($imagewidth, $imageheight, $imageType) = getimagesize($image);
 $imageType = image_type_to_mime_type($imageType);
 $newImageWidth = ceil($width * $scale);
 $newImageHeight = ceil($height * $scale);
 $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
 switch($imageType) {
  case "image/gif":
   $source=imagecreatefromgif($image); 
   break;
     case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
   $source=imagecreatefromjpeg($image); 
   break;
     case "image/png":
  case "image/x-png":
   $source=imagecreatefrompng($image); 
   break;
   }
 imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
 
 switch($imageType) {
  case "image/gif":
     imagegif($newImage,$image); 
   break;
       case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
     imagejpeg($newImage,$image,90); 
   break;
  case "image/png":
  case "image/x-png":
   imagepng($newImage,$image);  
   break;
    }
 
 chmod($image, 0777);
 return $image;
}
Resize Thumbnail Image Function

function resizeImage($image,$width,$height,$scale) {
 list($imagewidth, $imageheight, $imageType) = getimagesize($image);
 $imageType = image_type_to_mime_type($imageType);
 $newImageWidth = ceil($width * $scale);
 $newImageHeight = ceil($height * $scale);
 $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
 switch($imageType) {
  case "image/gif":
   $source=imagecreatefromgif($image); 
   break;
     case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
   $source=imagecreatefromjpeg($image); 
   break;
     case "image/png":
  case "image/x-png":
   $source=imagecreatefrompng($image); 
   break;
   }
 imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
 
 switch($imageType) {
  case "image/gif":
     imagegif($newImage,$image); 
   break;
       case "image/pjpeg":
  case "image/jpeg":
  case "image/jpg":
     imagejpeg($newImage,$image,90); 
   break;
  case "image/png":
  case "image/x-png":
   imagepng($newImage,$image);  
   break;
    }
 
 chmod($image, 0777);
 return $image;
}
function getHeight($image) {
 $size = getimagesize($image);
 $height = $size[1];
 return $height;
}
//You do not need to alter these functions
function getWidth($image) {
 $size = getimagesize($image);
 $width = $size[0];
 return $width;
}

if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
 //Get the new coordinates to crop the image.
 $x1 = $_POST["x1"];
 $y1 = $_POST["y1"];
 $x2 = $_POST["x2"];
 $y2 = $_POST["y2"];
 $w = $_POST["w"];
 $h = $_POST["h"];
 //Scale the image to the thumb_width set above
 $scale = $thumb_width/$w;
 $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
 //Reload the page again to view the thumbnail
 header("location:".$_SERVER["PHP_SELF"]);
 exit();
}


if ($_GET['a']=="delete" && strlen($_GET['t'])>0){
//get the file locations 
 $large_image_location = $upload_path.$large_image_prefix.$_GET['t'];
 $thumb_image_location = $upload_path.$thumb_image_prefix.$_GET['t'];
 if (file_exists($large_image_location)) {
  unlink($large_image_location);
 }
 if (file_exists($thumb_image_location)) {
  unlink($thumb_image_location);
 }
 header("location:".$_SERVER["PHP_SELF"]);
 exit(); 
}
view.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
 <meta name="generator" content="WebMotionUK" />
 <title>WebMotionUK - PHP &amp; Jquery image upload &amp; crop</title>
 <script type="text/javascript" src="js/jquery-pack.js"></script>
 <script type="text/javascript" src="js/jquery.imgareaselect.min.js"></script>
</head>
<body>

PHP Image delete Common Function Jquery Ajax Call

PHP Image delete Common Function Jquery Ajax Call


Today Discussed PHP Image delete Common Function Jquery Ajax Call Normal Core PHP Commonly Write one function just put table name and primary id and path get delete the image and unlink this page follows code.

PHP Image delete Common Function Jquery Ajax Call
PHP Image delete Common Function Jquery Ajax Call


Form.php

 <div class="col-md-6" id="delimage">
                                    <label> </label>
                                    <?php if (getprofile('image', $_SESSION['UID']) != '') { ?>
                                                                                        <img src="<?php echo $sitename . 'pages/profile/image/' . getprofile('image', $_SESSION['UID']); ?>" style="padding-bottom:10px;" height="100" /><!--&nbsp;<buttton type="button" style="cursor:pointer;" class="btn btn-danger" name="del" id="del" onclick="javascript:dellocationimage();"><i class="fa fa-close">&nbsp;Delete Image</i></buttton>-->
                                        <button type="button" style="cursor:pointer;" class="btn btn-danger" name="del" id="del" onclick="javascript:deleteimage('<?php echo getprofile('image', $_SESSION['UID']); ?>', '<?php echo $_SESSION['UID']; ?>', 'manageprofile', '../pages/profile/image/', 'image', 'pid');"><i class="fa fa-close">&nbsp;Delete Image</i></button>
                                    <?php } ?>
                                </div>
Ajax.js(Javascript)
function deleteimage(a, b, c, d, e, f)
{
    if (window.XMLHttpRequest)
    {
        oRequestsubcat = new XMLHttpRequest();
    } else if (window.ActiveXObject)
    {
        oRequestsubcat = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (a != '' && b != '' && c != '' && d !='' && e !=''&& f !='')
    {
        document.getElementById("delimage").innerHTML = '<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>';
        oRequestsubcat.open("POST", Settings.base_url + "config/functions_ajax.php", true);
        oRequestsubcat.onreadystatechange = delimg;
        oRequestsubcat.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        oRequestsubcat.send("image=" + a + "&id=" + b + "&table=" +c + "&path=" + d + "&images=" +e + "&pid=" + f);
        console.log(a,b,c,d,e,f);
    }
}
function delimg()
{
    if (oRequestsubcat.readyState == 4)
    {
        if (oRequestsubcat.status == 200)
        {
            document.getElementById("delimage").innerHTML = oRequestsubcat.responseText;
        }
        else
        {
            document.getElementById("delimage").innerHTML = oRequestsubcat.responseText;
        }
    }
}
or

Ajax.js(Jquery)
function deleteimage(a,b,c,d)
{
    $.post(Settings.base_url + "config/functions_ajax.php",{ a:a,b:b,c:c,d:d },function(data){
        console.log(data);
        $('#delimage').html(data);
        //alert(data);
    });
}

Function.php

if (($_REQUEST['image'] != '') && ($_REQUEST['id'] != '') && ($_REQUEST['table'] != '')&& ($_REQUEST['path'] != '')&& ($_REQUEST['images'] != '')&& ($_REQUEST['pid'] != '')) {
    unlink($_REQUEST['path'].$_REQUEST['image']);
 // $s = "UPDATE `".$_REQUEST['table']."` SET `".$_REQUEST['images']."`='' WHERE `".$_REQUEST['pid']."`='" . $_REQUEST['id'] . "'";
   // echo $s;
    //return $s;
   // exit;
    DB("UPDATE `".$_REQUEST['table']."` SET `".$_REQUEST['images']."`='' WHERE `pid`='" . $_REQUEST['id'] . "'");
    DB("INSERT `history` (`page`,`pageid`,`action`,`userid`,`ip`,`actionid`,`info`) VALUES ('Manage Profile','9','Delete','" . $_SESSION['UID'] . "','" . $_SERVER['REMOTE_ADDR'] . "','" . $_REQUEST['b'] . "','Image Deletion')");
  echo '<div class="alert alert-danger alert-dismissible"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><h4><i class="icon fa fa-close"></i>Succesfully Deleted</h4><!--<a href="' . $sitename . 'settings/adddepartment.htm">Add another one</a>--></div>';

PHP Security ImagesCaptcha

PHP security imagesCaptcha

PHP Security imagesCaptcha is a simple test to determine if a user is a computer or a human.  It is used to prevent spam abuse on the websites. Just Avoid spamers and crackers in the sites. So if you use CAPTCHA on your web forms, this can help in stopping some bots and making life harder for other bots in accessing or using your forms. Normal Core PHP simple Shopping Cart

PHP security imagesCaptcha
PHP security imagesCaptcha


Captcha.php

<?php
session_start();
class CaptchaSecurityImages {

 var $font = 'monofont.ttf';

 function generateCode($characters) {
  /* list all possible characters, similar looking characters and vowels have been removed */
  $possible = '23456789bcdfghjkmnpqrstvwxyz';
  $code = '';
  $i = 0;
  while ($i < $characters) { 
   $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
   $i++;
  }
  return $code;
 }

 function CaptchaSecurityImages($width='60',$height='50',$characters='5') {
  $code = $this->generateCode($characters);
  /* font size will be 75% of the image height */
  $font_size = $height * 0.85;
  $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, 20, 40, 100);
  $noise_color = imagecolorallocate($image, 200, 200, 200);
  /* generate random dots in background */
  for( $i=0; $i<($width*$height)/3; $i++ ) {
   imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
  }
  /* generate random lines in background */
  for( $i=0; $i<($width*$height)/150; $i++ ) {
   imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
  }
  /* create textbox and add text */
  $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
  $x = ($width - $textbox[4])/2;
  $y = ($height - $textbox[5])/2;
  imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
  /* output captcha image to browser */
  header('Content-Type: image/jpeg');
  imagejpeg($image);
  imagedestroy($image);
  $_SESSION['keycode'] = $code;
 }

}

$width = isset($_GET['width']) ? $_GET['width'] : '90';
$height = isset($_GET['height']) ? $_GET['height'] : '21';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '5';

$captcha = new CaptchaSecurityImages($width,$height,$characters);

?>
Your Form Page Added Following Script.
<script type="text/javascript">

function refreshCaptcha(abspath){

document.getElementById('refcaptimg').src="Captcha.php?t=" + new Date().getTime();

}</script>
Form

<form name="frmContact" method="post" action="contact-us.html">
<table width="175" border="0" cellpadding="2" cellspacing="0">
 <tr>
   <td  height="81" align="left" valign="middle"><a href="full_certificate.pdf" target="_blank"><img src="images/svc.gif" alt="" border="0"/></a></td>

  </tr>
<tr>

<td style="padding-bottom:10px;">
<div>
<!-- End Comm100 Live Chat Button Code -->

</td>
  </tr>

  <tr>
    <td class="page_heading"> </td>
  </tr>
  <tr>

   <td class="fnt_sml" style="padding-top:10px;"><img src="images/FORM/OPT-1.png" width="39" height="8" /><span style="color:#FF0000"></span></td>
  </tr>
  <tr>
   <td  ><input type="text" name="Name" id="Name" class="input_left" value='<?php echo $LastName?>' />
<span style="clear:left;" class="input_left_error" ><?php echo $msgName?></span></td>
  </tr>
 <tr>
    <td class="fnt_sml"><img src="images/FORM/OPT-3.png" /></span></td>

  </tr>
  <tr>
    <td><input type="text" name="Email" id="Email" class="input_left" value='<?php echo $Email ?>' />

<span style="clear:left;" class="input_left_error" ><?php echo $msgEmail ?></span></td>

  </tr>
  <tr>
    <td class="fnt_sml"><img src="images/FORM/OPT-4.png" /></td>
  </tr>
  <tr>
    <td><input type="text" name="Phone" id="Phone" class="input_left" value='<?php echo $Phone ?>' />

<span style="clear:left;" class="input_left_error" ><?php echo $msgPhone ?></span></td>

  </tr>
  <tr>
   <td class="fnt_sml"><img src="images/FORM/OPT-5.png" width="57" height="10" /></td>

  </tr>
  <tr>
    <td class="fnt_sml"><input type="text" name="TelPhone" class="input_left" id="TelPhone" value='<?php echo $TelPhone?>' />
    <span style="clear:left;" class="input_left_error"><?php echo $msgTelPhone ?></span></td>
  </tr>
 <tr>
   <td class="fnt_sml"><img src="images/FORM/OPT-2.png" /></td>

  </tr>
  <tr>
    <td><textarea name="Message" id="Message" rows="5" cols="25" class="input_left" value='<?php echo $Message?>'></textarea>

<span style="clear:left;" class="input_left_error" ><?php echo $msgMessage ?></span></td>
   </tr>
  <tr>
    <td class="fnt_sml"><img src="images/FORM/OPT-6.png" width="89" height="8" /></td>

  </tr>
  <tr>
    <td align="center"><input type="text" name="keycode" id="keycode" size="20" class="input_left" style="width:170px;" value='<?php echo $keycode ?>' />

<span style="clear:left;" class="input_left_error" > <?php echo $msgkeycode ?> </span>

<img src="CaptchaSecurityImages.php" id="refcaptimg" align="middle" style="margin-top:5px;" alt="" />&nbsp;<a href="javascript:refreshCaptcha('images/')"><img  src="images/hip_reload.gif" width="22" height="22" border="0" align="middle" style="margin-top:1px;" alt="" /></a>
          <a href="javascript:refreshCaptcha('images/')"><span class="style1" style="color: #FE4819"></span></a>

      <div class="input_left_error"></div></td>
  </tr>
  <tr>
    <td align="center"><input type="submit" name="Submit" value="Submit" style="background-color:#2172B8; color:#ffffff; border:solid 1px #2172B8;" />
</td>
</tr>
</table>
</form>

PHP Code Follow us : Contact-us.php

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

if(empty($_POST[Name])){$msgName='Please Enter Your Name.'; $Name= false;}
 else{$Name=$_POST[Name];}

if(empty($_POST[Message])) {$msgMessage= 'Please Enter your message.'; $Message=false; }
       else{$Message=$_POST[Message];}

if(empty($_POST[Email])){$msgEmail='Please Enter Your Email-Id';$Email= false; }
 else{$Email=$_POST[Email];}
 if (!eregi("^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$", $_POST[Email])){ $msgEmail= 'Please Enter A Valid Email Address'; $Email = false; }
 else{$Email=$_POST[Email];}

if(empty($_POST[Phone])){$msgPhone='Please Enter Your Contact No. '; $Phone= false;}
 else{$Phone=$_POST[Phone];}
 if(!eregi("[0-9.-\+]", $_POST[Phone])) {$msgPhone='Please enter a valid contact no. '; $Phone=false;}
 else{ $Phone=$_POST[Phone];}

 $TelPhone=$_POST[TelPhone];

if($_POST[keycode]!=$_SESSION[keycode] OR $_SESSION[keycode]==''){$msgkeycode = 'Incorrect verification code';$keycode = false;}
 else{$keycode=$_POST[keycode];}
 if($Name  && $Message && $Email && $Phone && $Message && $keycode)
 {
  header("Location: $tpage");
exit;
}else{ index.php } ?>

Convert Your WordPress theme to HTML 5

Convert Your WordPress Theme to HTML 5


Convert Your WordPress (Theme to HTML 5) Site customized your theme and your choose modify convert this theme html version today discussed this task. HTML 5 is a great set of new features and easy options.  Soon it will have the full support of most browsers in use today.  Eventually everyone will have to convert WordPress themes from XHTML to HTML5. wordpress Random display post
Convert Your WordPress theme to HTML 5


Pages:

  • header.php
  • index.php
  • sidebar.php:
  • footer.php
  • single.php (Optional)

Basic HTML5 Layout


<!DOCTYPE html>
<html lang="en">
<head>
    <title>TITLE | Dev2tricks!</title>
</head>
<body>
    <nav role="navigation"></nav>
<!--Ending header.php-->
<!--Begin  index.php-->
    <section id="content">
        <article role="main">
            <h1>Title of the Article</h1>
            <time datetime="YYYY-MM-DD"></time>
            <p>Some lorem ispum text of your post goes here.</p>
            <p>The article's text ends.</p>
        </article>
         
        <aside role="sidebar">
            <h2>Some Widget in The Sidebar</h2>
        </aside>
    </section>
<!--Ending index.php-->
<!--begin  footer.php-->
    <footer role="foottext">
        <small>Some Copyright info</small>
    </footer>
</body>
</html> 

Step 1 Converting header.php to HTML5


Now I will show you the code commonly used in the header.php of XHTML WordPress themes.


XHTML Theme header.php

<!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>
<title>My  Blog</title>
<?php wp_head(); ?>
</head>
<body>
<!-- Header  -->
<div class="header">
    <div class="container">
        <h1><a href="<?php bloginfo('url');?>">My Blog is Working Great.</a></h1>
    </div><!-- End  Container -->
</div><!-- End  Header -->
 
 
<!-- Navigation Bar Starts -->
<div class="navbar">
    <div class="container">
        <ul class="grid nav_bar">
            <?php wp_list_categories('navs_li='); ?>
         </ul>
    </div>
</div>
<!-- Navigation Bar Ends -->
<div class="container">


HTML5 header.php (Conversion)


Read the code and then follow the instructions below to convert your theme's header.php to HTML5.

<!doctype html>
<html>
<head>
<title>My Blog</title>
<?php wp_head(); ?>
</head>
<body>
<!-- Header -->
<header>
    <div class="container">
        <h1 class="grid"><a href="<?php bloginfo('url');?>">My Blog is Working Great.</a></h1>
    </div>
</header>
<!-- End Header  -->
  
<!-- Navigation Bar Starts-->
<nav>
    <div class="navbar">
        <ul class="grid nav_bar">
            <?php wp_list_categories('title_li='); ?>
         </ul>
    </div>
</nav>
<!-- Navigation Bar Ends -->
<section class="container">

Step 2 Converting index.php to HTML5

Converting first home page or index.php a common XHTML index.php consists of the following tags.  i will convert each of them follow us I will explain the whole process after conversion.


XHTML index.php

<div id="container">
<div id="content">
<div id="entries">
<div id="post">...</div>
 
</div><!--Ending Entries-->
<?php get_sidebar(); ?>
</div><!--Ending content-->
</div><!--Ending container-->
<?php get_footer(); ?>

HTML5 index.php (Conversion)

<div id="container">
    <div id="content">
        <section id="entries">
            <article id="post">...</article>
        </section><!--end entries-->
        <?php get_sidebar(); ?>
    </div><!--end content-->
</div><!--end wrap-->
<?php get_footer(); ?>

Complete Index.php in HTML5

<section class="entries">
  <?php if (have_posts()) : while (have_posts()) : the_post();
   
<article class="post" id="post-<?php the_ID(); ?>">
    <aside class="post_image">
        <?php
        if ( has_post_thumbnail() ) { 
            the_post_thumbnail();
        } else { ?>
            <a href="<?php the_permalink() ?>"><img src="<?php bloginfo('template_directory');?>/images/noImage.gif" title="<?php the_title(); ?>" /></a>
        <?php }?>
    </aside>
    <section class="post_content">
        <h1><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
        <p><?php echo get_the_excerpt(); ?></p>
        <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>" class="read_more ">Read More</a>
    </section>
    <section class="meta">
  
    <p> <?php the_category(',') ?></p>
  
    <p><?php the_tags(""); ?></p>
  
    </section>
</article>
  <?php endwhile; else: ?>
  <p>
    <?php _e('Sorry, no posts matched your criteria.'); ?>
  </p>
  <?php endif; ?>
  
  <?php posts_nav_link(' ⏼ ', __('« Newer Posts'), __('Older Posts »')); ?>
</section>


How to create and download a csv file from php script?

How to create and download a csv file from php script?

Today discussed just core php while loop some data stored and display more then data just export download csv or pdf other format document. Here i try this code. this example code format csv export data.
How to create and download a csv file from php script?
How to create and download a csv file from php script?

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line)
}
header dialog you will have to  send http header like this example header

header('Content-Disposition: attach
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}
array_to_csv_download(array(
  array(1,2,3,4), // this array is going to be the first row
  array(1,2,3,4)), // this array is going to be the second row
  "numbers.csv"
);


Instead of the php://memory you can  also use the php://output for the file descriptor and do away with the seeking and such
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}   

Top 5 Most Popular WordPress Plugin

Top 5 Most Popular WordPress Plugin

Most Popular Plugin The following contains a list of the top 5 most popular WordPress Plugins that have been detected by WordPress Theme.

1. Yoast WordPress SEO Plugin

Yoast WordPress SEO
Yoast WordPress SEO

Easily optimize your WordPress site with one plugin and Real time content analysis functionality and many more features to streamline your site.a Premium Yoast seo plugin for even same but more features and support seo. Read More


2.Contact Form 7
Contact Form7
Contact Form7


Contact Form 7 can manage multiple contact forms, plus you can customize the form and the mail contents flexibly with simple markup. The form supports Ajax-powered submitting, CAPTCHA, Akismet spam filtering and so on.  Read More


3.All In One SEO Pack


All In One SEO
All In One SEO
The most downloaded plugin for WordPress (almost 30 million downloads). Use All in One SEO Pack to automatically optimize your site for Search Engines Read More

4. Js_composer

Js_Composer
Js_Composer

Visual Composer is the #1 best selling frontend and beackend drag and drop page builder Read More

5.Woocommerce

Woocommerce
Woocommerce

Wordpress Woocommerce site Your page selling product and more selling website very easily product added and cart page check out in your site.  Read More

Paypal Integration With PHP & MYSQL

PAYPAL INTEGRATION WITH PHP & MYSQL


Paypal Integration
Paypal Integration
Previously Discussed Simple PHP shopping cart stored a cart payment integration is discussed Follow us
Simple Way to PHP Paypal Integration following steps.

Step : 1

First Setup your Paypal Account

Signup Paypal Account if you don't already have one.  In order to use PIN, the paypal account you are selling from must be a Business Account

Select ‘edit profile’ from your PayPal account and check the following settings.

Under ‘My Selling Preferences’ >> ‘Getting paid and managing risk’ >> ‘Instant Payment Notification Preferences’
  1. Set the IPN value to ‘On’
  2. Set the IPN URL to the PHP page containing the IPN code shown in steps 3 & 4 of this tutorial. (http://www.example.com/payment.php)
Step : 2

Your Website Looking UI design and must now send all required value to paypal so that the payment can be processed.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Paypal Integration Test</title>
</head>
<body>
<form class="paypal" action="payments.php" method="post" id="paypal_form" target="_blank">
<input type="hidden" name="command" value="_xclick" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="lc" value="UK" />
<input type="hidden" name="currency_code" value="GBP" />
<input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
<input type="hidden" name="first_name" value="Customer's First Name" />
<input type="hidden" name="last_name" value="Customer's Last Name" />
<input type="hidden" name="payer_email" value="customer@example.com" />
<input type="hidden" name="item_number" value="123456" / >
<input type="submit" name="submit" value="Submit Payment"/>
</form>
</body>
</html>

Step:3 

Paymen Page REQUEST 

// Database variables
$hostname = "localhost"; //database location
$username = ""; //database username
$password = ""; //database password
$db_name = ""; //database name
// PayPal settings
$paypal_email = 'user@domain.com';
$return_url = 'http://domain.com/payment-successful.html';
$cancel_url = 'http://domain.com/payment-cancelled.html';
$notify_url = 'http://domain.com/payments.php';
$item_name = 'Test Item';
$item_amount = 5.00;
// Include Functions
include("functions.php");
// Check if paypal request or response
if (!isset($_POST["txn_id"]) &amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp; !isset($_POST["txn_type"])){
    $querystring = '';
    // Firstly Append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&amp;amp;amp;amp;amp;amp;";
    // Append amount&amp;amp;amp;amp;amp;amp; currency (£) to quersytring so it cannot be edited in html
    //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&amp;amp;amp;amp;amp;amp;";
    $querystring .= "amount=".urlencode($item_amount)."&amp;amp;amp;amp;amp;amp;";
    //loop for posted values and append to querystring
    foreach($_POST as $key =&amp;amp;amp;amp;amp;gt; $value) {
        $value = urlencode(stripslashes($value));
        $querystring .= "$key=$value&amp;amp;amp;amp;amp;amp;";
    }
    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&amp;amp;amp;amp;amp;amp;";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&amp;amp;amp;amp;amp;amp;";
    $querystring .= "notify_url=".urlencode($notify_url);
    // Append querystring with custom field
    //$querystring .= "&amp;amp;amp;amp;amp;amp;custom=".USERID;
    // Redirect to paypal IPN
    header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
    exit();
} else {
   // Response from PayPal
}
Step: 4 

Payment Page Response

 // Database variables
$hostname = "localhost"; //database location
$username = ""; //database username
$password = ""; //database password
$db_name = ""; //database name

// PayPal settings
$paypal_email = 'user@domain.com';
$return_url = 'http://domain.com/payment-successful.html';
$cancel_url = 'http://domain.com/payment-cancelled.html';
$notify_url = 'http://domain.com/payments.php';

$item_name = 'Test Item';
$item_amount = 5.00;

// Include Functions
include("functions.php");

// Check if paypal request or response
if (!isset($_POST["txn_id"]) &amp;amp;amp;&amp;amp;amp; !isset($_POST["txn_type"])){
    $querystring = '';
    
    // Firstly Append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&amp;amp;amp;";
    
    // Append amount&amp;amp;amp; currency (£) to quersytring so it cannot be edited in html
    
    //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&amp;amp;amp;";
    $querystring .= "amount=".urlencode($item_amount)."&amp;amp;amp;";
    
    //loop for posted values and append to querystring
    foreach($_POST as $key =&amp;amp;gt; $value){
        $value = urlencode(stripslashes($value));
        $querystring .= "$key=$value&amp;amp;amp;";
    }
    
    // Append paypal return addresses
    $querystring .= "return=".urlencode(stripslashes($return_url))."&amp;amp;amp;";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&amp;amp;amp;";
    $querystring .= "notify_url=".urlencode($notify_url);
    
    // Append querystring with custom field
    //$querystring .= "&amp;amp;amp;custom=".USERID;
    
    // Redirect to paypal IPN
    header('location:https://www.sandbox.paypal.com/cgi-bin/webscr'.$querystring);
    exit();
} else {
    //Database Connection
    $link = mysql_connect($host, $user, $pass);
    mysql_select_db($db_name);
    
    // Response from Paypal

    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key =&amp;amp;gt; $value) {
        $value = urlencode(stripslashes($value));
        $value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}',$value);// IPN fix
        $req .= "&amp;amp;amp;$key=$value";
    }
    
    // assign posted variables to local variables
    $data['item_name']          = $_POST['item_name'];
    $data['item_number']        = $_POST['item_number'];
    $data['payment_status']     = $_POST['payment_status'];
    $data['payment_amount']     = $_POST['mc_gross'];
    $data['payment_currency']   = $_POST['mc_currency'];
    $data['txn_id']             = $_POST['txn_id'];
    $data['receiver_email']     = $_POST['receiver_email'];
    $data['payer_email']        = $_POST['payer_email'];
    $data['custom']             = $_POST['custom'];
        
    // post back to PayPal system to validate
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
    
    $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
    
    if (!$fp) {
        // HTTP ERROR
        
    } else {
        fputs($fp, $header . $req);
        while (!feof($fp)) {
            $res = fgets ($fp, 1024);
            if (strcmp($res, "VERIFIED") == 0) {
                
                // Used for debugging
                // mail('user@domain.com', 'PAYPAL POST - VERIFIED RESPONSE', print_r($post, true));
                        
                // Validate payment (Check unique txnid &amp;amp;amp; correct price)
                $valid_txnid = check_txnid($data['txn_id']);
                $valid_price = check_price($data['payment_amount'], $data['item_number']);
                // PAYMENT VALIDATED &amp;amp;amp; VERIFIED!
                if ($valid_txnid &amp;amp;amp;&amp;amp;amp; $valid_price) {
                    
                    $orderid = updatePayments($data);
                    
                    if ($orderid) {
                        // Payment has been made &amp;amp;amp; successfully inserted into the Database
                    } else {
                        // Error inserting into DB
                        // E-mail admin or alert user
                        // mail('user@domain.com', 'PAYPAL POST - INSERT INTO DB WENT WRONG', print_r($data, true));
                    }
                } else {
                    // Payment made but data has been changed
                    // E-mail admin or alert user
                }
            
            } else if (strcmp ($res, "INVALID") == 0) {
            
                // PAYMENT INVALID &amp;amp;amp; INVESTIGATE MANUALY!
                // E-mail admin or alert user
                
                // Used for debugging
                //@mail("user@domain.com", "PAYPAL DEBUGGING", "Invalid Response
data =
&amp;amp;lt;pre&amp;amp;gt;".print_r($post, true)."&amp;amp;lt;/pre&amp;amp;gt;

");
            }
        }
    fclose ($fp);
    }
}


Step 5 - Function.php


// functions.php
function check_txnid($tnxid){
global $link;
return true;
$valid_txnid = true;
//get result set
$sql = mysql_query("SELECT * FROM `payments` WHERE txnid = '$tnxid'", $link);
if ($row = mysql_fetch_array($sql)) {
$valid_txnid = false;
}
return $valid_txnid;
}

function check_price($price, $id){
$valid_price = false;
//you could use the below to check whether the correct price has been paid for the product

/*
$sql = mysql_query("SELECT amount FROM `products` WHERE id = '$id'");
if (mysql_num_rows($sql) != 0) {
while ($row = mysql_fetch_array($sql)) {
$num = (float)$row['amount'];
if($num == $price){
$valid_price = true;
}
}
}
return $valid_price;
*/
return true;
}

function updatePayments($data){
global $link;

if (is_array($data)) {
$sql = mysql_query("INSERT INTO `payments` (txnid, payment_amount, payment_status, itemid, createdtime) VALUES (
'".$data['txn_id']."' ,
'".$data['payment_amount']."' ,
'".$data['payment_status']."' ,
'".$data['item_number']."' ,
'".date("Y-m-d H:i:s")."'
)", $link);
return mysql_insert_id($link);
}
}


Step: 6 Databast Table

Website Paypal Integration store payment details inset database table is most Important.

CREATE TABLE IF NOT EXISTS `payments` (
 `id` int(6) NOT NULL AUTO_INCREMENT,
 `txnid` varchar(20) NOT NULL,
 `payment_amount` decimal(7,2) NOT NULL,
 `payment_status` varchar(25) NOT NULL,
 `itemid` varchar(25) NOT NULL,
 `createdtime` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;