article

Wednesday, May 9, 2018

how to enabling mod rewrite in xampp

how to enabling mod rewrite in xampp

1. go to the directory of installation \apache\conf and edit httpd.conf.
2. Find the line which contains
3. #LoadModule rewrite_module modules/mod_rewrite.so
uncomment this(should be):
4. LoadModule rewrite_module modules/mod_rewrite.so
5. Also find AllowOverride None
6. Should be: AllowOverride All

Friday, May 4, 2018

PHP curl not installed - Getting cURL to Work in XAMPP

PHP curl not installed - Getting cURL to Work in XAMPP

1. Go to xampp install directory. xampp\php\php.ini
2. Go to php.ini in php directory.
3. Open php.ini and find curl, uncomment the first find you see. extension=php_curl.dll
4. Save and close file.
5. restart xampp
6. Done

Sunday, April 29, 2018

How to Load or Read XML file using PHP

How to Load or Read XML file using PHP
 
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Load or Read XML file using PHP</title>
</head>
<body>
<?php
//Read Specific XML Elements
  $xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
  echo $xmldata->employee[0]->firstname . "<br/>";
  echo $xmldata->employee[1]->firstname . "<br/>";
  echo $xmldata->employee[2]->firstname; 
?><br/><br/>
<?php
//Read XML Elements In A Loop
$xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
foreach($xmldata->children() as $empl) {         
 echo $empl->firstname . ", ";     
 echo $empl->lastname . ", ";     
 echo $empl->designation . ", ";        
 echo $empl->salary . "<br/>"; 
} 
?>
<br/><br/>
<?php
$xml = simplexml_load_file('xml/employee.xml');
echo '<h2>Employees Listing</h2>';
$list = $xml->employee;
for ($i = 0; $i < count($list); $i++) {
    echo 'Name: ' . $list[$i]->firstname . '<br>';
    echo 'Salary: ' . $list[$i]->salary . '<br>';
    echo 'Position: ' . $list[$i]->designation . '<br><br>';
}
?>
</body>
</html>
//employee.xml
<?xml version="1.0"?>
<company>
 <employee>
 <firstname>Emma</firstname>
 <lastname>Cruise</lastname>
 <designation>MD</designation>
 <salary>500000</salary>
 </employee>
 <employee>
 <firstname>Olivia</firstname>
 <lastname>Horne</lastname>
 <designation>CEO</designation>
 <salary>250000</salary>
 </employee> 
 <employee>
 <firstname>Isabella</firstname>
 <lastname>Sophia</lastname>
 <designation>Finance Manager</designation>
 <salary>250000</salary>
 </employee>
</company>

Saturday, April 28, 2018

Highlight table row record on hover - jQuery

Highlight table row record on hover - jQuery





<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Highlight table row record on hover - jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<h1>Highlight table row record on hover - jQuery</h1>
<table border="1">
  <tr><th>No</th><th>Name</th><th>Age</th><th>Salary</th></tr>
  <tr><td>1</td><td>Kenshin Himura</td><td>28</td><td>$100,000</td></tr>
  <tr><td>1</td><td>Kenshin Himura</td><td>28</td><td>$100,000</td></tr>
</table>
<script type="text/javascript">
$("tr").not(':first').hover(
 function () {
   $(this).css("background","#195A72");
 },
 function () {
   $(this).css("background","");
 }
);
</script>
</body>
</html>

Sunday, April 15, 2018

HTML5 Inline Edit with jQuery Ajax, PHP & MYSQL

HTML5 Inline Edit with jQuery Ajax, PHP & MYSQLi
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Inline Content Editing with jQuery, PHP & MYSQL</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
    var message_status = $("#status");
    $("td[contenteditable=true]").blur(function(){
        var field_userid = $(this).attr("id");
        var value = $(this).text();
  var string = value;
  $.post("ajax_inlineupdate.php", { string: string,field_userid: field_userid}, function(data) {
           if(data != '')
     {
   message_status.show();
   message_status.text(data);
   //hide the message
   setTimeout(function(){message_status.hide()},1000);
     }
        });
    });
});
</script>
<style>
table.zebra-style {
 font-family:"Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
 text-align:left;
 border:1px solid #ccc;
 margin-bottom:25px;
 width:50%
}
table.zebra-style th {
 color: #444;
 font-size: 13px;
 font-weight: normal;
 padding: 10px 8px;
}
table.zebra-style td {
 color: #777;
 padding: 8px;
 font-size:13px;
}
table.zebra-style tr.odd {
 background:#f2f2f2;
}
body {
 background:#fafafa;
}
.container {
 width: 800px;
 border: 1px solid #C4CDE0;
 border-radius: 2px;
 margin: 0 auto;
 height: 1300px;
 background:#fff;
 padding-left:10px;
}
#status { padding:10px; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:90%; }
</style>
</head>
<body>
  <h1>HTML5 Inline Edit with jQuery Ajax, PHP & MYSQLi</h1>
  <div id="status"></div>
<table class="table zebra-style">
    <thead>
      <tr>
        <th>#</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>City</th>
      </tr>
    </thead>
    <tbody>
      <tr class="odd">
        <td>1</td>
        <td id="f:1" contenteditable="true">Michael</td>
        <td id="l:1" contenteditable="true">Holz</td>
        <td id="c:1" contenteditable="true">Olongapo City</td>
      </tr>
      <tr>
        <td>2</td>
        <td id="f:2" contenteditable="true">Paula</td>
        <td id="l:2" contenteditable="true">Wilson</td>
        <td id="c:2" contenteditable="true">California</td>
      </tr>
      <tr class="odd">
        <td>3</td>
        <td id="f:3" contenteditable="true">Antonio</td>
        <td id="l:3" contenteditable="true">Moreno</td>
        <td id="c:3" contenteditable="true">Olongapo City</td>
      </tr>
    </tbody>
 </table>
</body>
</html>
//ajax_inlineupdate.php
<?php
include"dbcon.php"; 
$string  = $_POST['string']; 
$field_userid  = $_POST['field_userid']; 
if ($string==''){
 echo "<p class='btn btn-info' align='center'>Please Insert field</p>";
}else{
 $strings = $field_userid;
 $fields = $strings[0]; 
 if ($fields=='f') {
  $setrs = "fname='$string'"; 
 }elseif ($fields=='l') {
  $setrs = "lname='$string'"; 
 }elseif ($fields=='c') {
  $setrs = "city='$string'"; 
 }else{$setrs = "";} 
 $getid = substr($field_userid, 2); 
 $sql = "UPDATE user SET $setrs WHERE id = '$getid' ";
 if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
 } else {
  echo "Error updating record: " . $conn->error;
 }  
} 
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Friday, April 13, 2018

PHP Function create SEO URL Friendly

PHP Function create SEO URL Friendly

strtlower make string lowercase preg_replace remove all unwanted character spaces and dashes
<?php
function seo_url($string, $seperator='-') {
   $string = strtolower($string);
   $string = preg_replace("/[^a-z0-9_\s-]/", $seperator, $string);
   $string = preg_replace("/[\s-]+/", " ", $string);
   $string = preg_replace("/[\s_]/", $seperator, $string);
   return $string;
}
$teststring = "PHP Function create SEO URL Friendly";
$seofrieldy = seo_url($teststring);
echo "www.tutorial.com/$seofrieldy/";
?>

Saturday, March 31, 2018

Dynamic Select Box using Jquery Ajax php mysql

Dynamic Select Box using Jquery Ajax php mysql

How to create a dynamic select box using jquery ajax php and mysql



Database
CREATE TABLE `rme_city` (
  `idarea` int(11) NOT NULL,
  `city` varchar(255) NOT NULL,
  `contryid` varchar(200) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `rme_city` (`idarea`, `city`, `contryid`) VALUES
(1, 'Oakland', '4'),
(2, 'San Diego', '4'),
(21, 'Birmingham', '1'),
(22, 'Montgomery', '1');

ALTER TABLE `rme_city`
  MODIFY `idarea` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;

index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Select Box using Jquery Ajax php mysqli</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
         $(document).ready(function()
         {
          $(".country").change(function()
          {
           var id=$(this).val();
           var dataString = 'id='+ id;
           $.ajax
           ({
            type: "POST",
            url: "city.php",
            data: dataString,
            cache: false,
            success: function(html)
            {
             $(".city").html(html);
            }
           });
          });
         });
</script> 
</head>
<body>
 <p>State : 
		 <select name="country" class="country select" style="width:250px" >
			<option value="1">Alabama</option>
			<option value="2">Alaska</option>
			<option value="3">Arizona</option>
			<option value="4" selected>California</option>
			<option value="5">Colorado</option>
			<option value="6">Connecticut</option>
			<option value="7">Florida</option>
			<option value="8">Georgia</option>
         </select></p>  
<p>City :
		 <select name="city" style="width:250px" class="city select">
          <option value="" selected="selected" >Please Select Your Area</option>
         </select></p>		 
</body>
</html>

city.php
<?php
$mysqli = new mysqli('localhost','root','','testingdb');
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
if($_POST['id'])
{
	$id=$_POST['id'];
	$results = $mysqli->query("SELECT * FROM rme_city where contryid='$id' ORDER BY city ASC");
	while($row = $results->fetch_assoc()) {
		$id=$row['idarea'];
		$data=$row['city'];
		echo '<option value="'.$id.'">'.$data.'</option>';
	}
}
?>

Saturday, March 24, 2018

Multiple Image Upload Php

Multiple Image Upload Php

how to upload multiple files using a single form



<?php
if (isset($_POST['Submit'])){
while(list($key,$value) = each($_FILES['images']['name']))
 {
  if(!empty($value))
  {
   $filename = $value;
    $filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line
    $add = "img/$filename";
    copy($_FILES['images']['tmp_name'][$key], $add);
    chmod("$add",0777);
  }
 }
}
?>
<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>
<form method=post action="" enctype='multipart/form-data'>
<?php
$max_no_img=4;
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]'></td></tr>";
}
?>
<tr><td colspan=2 align=center><input name="Submit" type=submit value='Add Image'></td></tr>
</form>
</table>

Saturday, March 3, 2018

jQuery PHP checkbox values to PHP $_POST variables

jQuery PHP checkbox values to PHP $_POST variables




 
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery PHP checkbox values to PHP $_POST variables</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function () {
    $('#submitBtn').click (function() {
        var selected = new Array();
   $("input:checkbox[name=programming]:checked").each(function() {
    selected.push($(this).val());
   });
  var selectedString = selected.join(",");
        $.post("ajaxcheckboxvalue.php", {selected: selected },
        function(data){
            $('.result').html(data);
        });  
    });
});
</script>
</head>
<body>
<div class="container">
 <div class="row">
     <div class="col-md-6 offset-md-3">
  <h1>jQuery PHP checkbox values to PHP $_POST variables</h1>
  <div class="card" style="margin:50px 0">
                <div class="card-header">Checkbox Animation</div>
    <ul class="list-group list-group-flush">
                    <li class="list-group-item">
                        Bootstrap Checkbox Default
                                <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Default"/>
                                        <span class="default"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Primary
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Primary"/>
                                        <span class="primary"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Success
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Success"/>
                                        <span class="success"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Info
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Info"/>
                                        <span class="info"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Warning
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Warning"/>
                                        <span class="warning"></span>
                                    </label>
                    </li>
                    <li class="list-group-item">
                        Bootstrap Checkbox Danger
                                    <label class="checkbox">
                                        <input type="checkbox" name="programming" value="Bootstrap Checkbox Danger"/>
                                        <span class="danger"></span>
                                    </label>
                    </li>
                </ul>
    <div class = "result" style="padding:10px;"></div>
    <button type="button" id = "submitBtn" class="btn btn-outline-success slideright" style="margin:10px;">Submit</button> 
  </div>  
  </div>
 </div>
</div>
<style>
  @keyframes check {0% {height: 0;width: 0;}
    25% {height: 0;width: 10px;}
    50% {height: 20px;width: 10px;}
  }
  .checkbox{background-color:#fff;display:inline-block;height:28px;margin:0 .25em;width:28px;border-radius:4px;border:1px solid #ccc;float:right}
  .checkbox span{display:block;height:28px;position:relative;width:28px;padding:0}
  .checkbox span:after{-moz-transform:scaleX(-1) rotate(135deg);-ms-transform:scaleX(-1) rotate(135deg);-webkit-transform:scaleX(-1) rotate(135deg);transform:scaleX(-1) rotate(135deg);-moz-transform-origin:left top;-ms-transform-origin:left top;-webkit-transform-origin:left top;transform-origin:left top;border-right:4px solid #fff;border-top:4px solid #fff;content:'';display:block;height:20px;left:3px;position:absolute;top:15px;width:10px}
  .checkbox span:hover:after{border-color:#999}
  .checkbox input{display:none}
  .checkbox input:checked + span:after{-webkit-animation:check .8s;-moz-animation:check .8s;-o-animation:check .8s;animation:check .8s;border-color:#555}
.checkbox input:checked + .default:after{border-color:#444}
.checkbox input:checked + .primary:after{border-color:#2196F3}
.checkbox input:checked + .success:after{border-color:#8bc34a}
.checkbox input:checked + .info:after{border-color:#3de0f5}
.checkbox input:checked + .warning:after{border-color:#FFC107}
.checkbox input:checked + .danger:after{border-color:#f44336}
</style>
</body>
</html>
//ajaxcheckboxvalue.php
<?php
$selected  = $_POST['selected'];
foreach ($selected as $value) {
    echo $value . " <br/>";

}
?>

Saturday, February 24, 2018

Create a PHP jQuery ajax and MySQLi LIKE Search

Create a PHP jQuery ajax and MySQLi LIKE Search






<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create a PHP jQuery ajax and MySQLi LIKE Search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $(".search_button").click(function() {
        // getting the value that user typed
        var searchString    = $("#search_box").val();
        // forming the queryString
        var data  = 'search='+ searchString;
        // if searchString is not empty
        if(searchString) {
            // ajax call
            $.ajax({
                type: "POST",
                url: "do_search.php",
                data: data,
                beforeSend: function(html) { // this happens before actual call
                    $("#results").html(''); 
                    $("#searchresults").show();
                    $(".word").html(searchString);
               },
               success: function(html){ // this happens after we get results
                    $("#results").show();
                    $("#results").append(html);
              }
            });    
        }
        return false;
    });
});
</script>
</head>
<body>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" /><br />
</form>
</div>  
<div>
 <div id="searchresults">Search results :</div>
 <div id="results" class="update"></div>
</div>
</div>
<style>
body{ font-family:Arial, Helvetica, sans-serif; }
#container { margin: 0 auto; width: 600px; }
#search_box { 
 padding:4px; 
 border:solid 1px #666666; 
 width:300px; 
 height:30px; 
 font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px; 
}
.search_button { 
 border:#000000 solid 1px; 
 padding: 6px; 
 color:#000; 
 font-weight:bold; 
 font-size:16px;-moz-border-radius: 6px;-webkit-border-radius: 6px; 
}
#searchresults { 
 text-align:left; 
 margin-top:20px; 
 display:none; 
 font-family:Arial, Helvetica, sans-serif; 
 font-size:16px; 
 color:#000;
}
#newspaper-b {
    font-family: lucida sans unicode,lucida grande,Sans-Serif;
    font-size: 12px;
    width: 480px;
    text-align: left;
    border-collapse: collapse;
    border: 1px solid #69c;
    margin: 20px;
}
.tr, tr {
    border-bottom: 1px solid #ddd;
}
#newspaper-b th {
    font-weight: 400;
    font-size: 14px;
    color: #039;
    padding: 15px 10px 10px;
}
#newspaper-b tbody {
    background: #e8edff;
}
#newspaper-b td {
    color: #669;
    border-top: 1px dashed #fff;
    padding: 10px;
}
#newspaper-b tbody tr:hover td{color:#339;background:#d0dafd}
.found { 
 font-weight: bold; 
 font-style: italic; 
 color: #ff0000;
}
</style>
</body>
</html>
//do_search.php
<table id="newspaper-b">
 <thead>
  <tr>
   <th scope="col">Name</th>
   <th scope="col">Category</th>
   <th scope="col">Price</th>
   <th scope="col">Discount</th>
  </tr>
 </thead>
 <tbody>
<?php
include("dbcon.php");
//if we got something through $_POST
if (isset($_POST['search'])) {
    // never trust what user wrote! We must ALWAYS sanitize user input
    $word = mysql_real_escape_string($_POST['search']);
    $word = htmlentities($word);
    // build your search query to the database
 $sql = "SELECT * FROM product WHERE name LIKE '%" . $word . "%' ORDER BY pid LIMIT 10";
 $result = mysqli_query($conn, $sql);
 if (mysqli_num_rows($result) > 0) {
        $end_result = '';
   while($row = mysqli_fetch_assoc($result)) {
   $rs_name = $row["name"];
   $category = $row["category"];
   $price = $row["price"];
   $discount = $row["discount"];
   $bold           = '<span class="found">' . $word . '</span>';    
            $end_result     .= '<tr><td>'. str_ireplace($word, $bold, $rs_name).'</td><td>'.$category.'</td><td>'.$price.'</td><td>'.$discount.'</td></tr>';
  }
        echo $end_result;
 }else {
  echo "0 results";
 }
}
?>
 </tbody>
</table>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Sunday, January 14, 2018

How to Add Widgets to WordPress Theme’s Footer

How to Add Widgets to WordPress Theme’s Footer

1. Register the footer widget area

Open the functions.php file from the WordPress Theme Editor and search for the following line of code:


register_sidebar

Add the following block of code just below the other sidebar registration code

function twentysixteen_widgets_init() {
 register_sidebar( array(
  'name'          => __( 'Sidebar', 'twentysixteen' ),
  'id'            => 'sidebar-1',
  'description'   => __( 'Add widgets here to appear in your sidebar.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) );

 register_sidebar( array(
  'name'          => __( 'Content Bottom 1', 'twentysixteen' ),
  'id'            => 'sidebar-2',
  'description'   => __( 'Appears at the bottom of the content on posts and pages.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) );

 register_sidebar( array(
  'name'          => __( 'Content Bottom 2', 'twentysixteen' ),
  'id'            => 'sidebar-3',
  'description'   => __( 'Appears at the bottom of the content on posts and pages.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) ); 
 register_sidebar( array(
  'name'          => __( 'Content Bottom 3', 'twentysixteen' ),
  'id'            => 'sidebar-4',
  'description'   => __( 'Appears at the bottom of the content on posts and pages.', 'twentysixteen' ),
  'before_widget' => '<section id="%1$s" class="widget %2$s">',
  'after_widget'  => '</section>',
  'before_title'  => '<h2 class="widget-title">',
  'after_title'   => '</h2>',
 ) ); 
}
add_action( 'widgets_init', 'twentysixteen_widgets_init' );


2. Show the footer widget area in your theme

Open your footer.php file and insert the following block of code where you want to show the footer widgets (this will show the 3 footer widget areas):

<div id="footer-sidebar" class="secondary">
<div id="footer-sidebar1">
 <?php
  if(is_active_sidebar('sidebar-2')){
  dynamic_sidebar('sidebar-2');
  }
 ?>
</div>
<div id="footer-sidebar2">
 <?php
 if(is_active_sidebar('sidebar-3')){
 dynamic_sidebar('sidebar-3');
 }
 ?>
</div>
<div id="footer-sidebar3">
 <?php
 if(is_active_sidebar('sidebar-4')){
 dynamic_sidebar('sidebar-4');
 }
 ?>
</div>
</div>

wp_nav_menu change sub-menu class name?

wp_nav_menu change sub-menu class name?

from <ul class="sub-menu"> to <ul class="dropdown-menu">

You can use WordPress preg_replace filter (in your theme functions.php file) example:

function new_submenu_class($menu) {    
    $menu = preg_replace('/ class="sub-menu"/',' class="dropdown-menu" ',$menu);        
    return $menu;      
}
add_filter('wp_nav_menu','new_submenu_class'); 

Sunday, June 11, 2017

Python Django - Admin Interface

Python Django - Admin Interface

Django provides a ready-to-use user interface for administrative activities. Django automatically generates admin UI based on your project models.

Starting the Admin Interface

The Admin interface depends on the django.countrib module. To have it working you need to make sure some modules are imported in the INSTALLED_APPS and MIDDLEWARE_CLASSES tuples of the myproject/settings.py file.

For INSTALLED_APPS make sure you have −

INSTALLED_APPS = (
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'myapp', #created application myapp folder
)

For MIDDLEWARE_CLASSES −

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Before launching your server, to access your Admin Interface, you need to initiate the database −

C:\myprojectdjango>python manage.py migrate

migrate will create necessary tables or collections depending on your db type, necessary for the admin interface to run.

Create user

C:\myprojectdjango>python manage.py createsuperuser

input username, email address and password
Superuser created succesfully

Now to start the Admin Interface, we need to make sure we have configured a URL for our admin interface. Open the myproject/url.py and you should have something like −
 
from django.conf.urls import patterns, include, url
from django.contrib import admin

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

Now just run the server.

 C:\myprojectdjango>python manage.py runserver

 And your admin interface is accessible at: http://127.0.0.1:8000/admin/

login using created username and password

Python Django - Install Create project and run

Python Django - Install Create project and run

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django makes it easier to build better web apps quickly and with less code.

You can download the latest version of Django from the link http://www.djangoproject.com/download 

Windows Installation

C:\>pip install Django==1.9.7
c:\>python -c "import django; print(django.get_version())"

Create a Project
c:\>django-admin startproject myprojectdjango

This will create a "myprojectdjango" folder with the following structure −
myprojectdjango/
   manage.py
   myproject/
      __init__.py
      settings.py
      urls.py
      wsgi.py

manage.py − This file is kind of your project local django-admin for interacting with your project via command line (start the development server, sync db...). To get a full list of command accessible via manage.py you can use the code −
__init__.py − Just for python, treat this folder as package.
settings.py − As the name indicates, your project settings.
urls.py − All links of your project and the function to call. A kind of ToC of your project.
wsgi.py − If you need to deploy your project over WSGI.

Setting Up Your Project
Your project is set up in the subfolder myproject/settings.py. Following are some important options you might need to set −

DEBUG = True

This option lets you set if your project is in debug mode or not. Debug mode lets you get more information about your project's error. Never set it to ‘True’ for a live project. However, this has to be set to ‘True’ if you want the Django light server to serve static files. Do it only in the development mode.

DATABASES = {
   'default': {
      'ENGINE': 'django.db.backends.sqlite3',
      'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
      'USER': '',
      'PASSWORD': '',
      'HOST': '',
      'PORT': '',
   }
}

Database is set in the ‘Database’ dictionary. The example above is for SQLite engine. As stated earlier, Django also supports −

MySQL (django.db.backends.mysql)
PostGreSQL (django.db.backends.postgresql_psycopg2)
Oracle (django.db.backends.oracle) and NoSQL DB
MongoDB (django_mongodb_engine)
Before setting any new engine, make sure you have the correct db driver installed.

Now that your project is created and configured make sure it's working −

c:\>myprojectdjango>python manage.py runserver

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Monday, May 29, 2017

Python Function and Loop Example code

Python Function and Loop Example code
 
#!/usr/bin/python

#A function is created with the def keyword
def function():
    pass
#-------------------------------------------------------   
def printme( str ):
   "This prints a passed string into this function"
   print (str)
   return
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
#-------------------------------------------------------
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   print ("Values inside the function before change: ", mylist)
   mylist[2]=50
   print ("Values inside the function after change: ", mylist)
   return

# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
#-------------------------------------------------------
# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print ("Name: ", name)
   print ("Age ", age)
   return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
#-------------------------------------------------------

print "1 + 1 =", 1 + 1
print "2 * (2 + 3) =", 2 * (2+3)
print "1.2 / 0.3 =", 1.2 / 0.3
print "5 / 2 =", 5 / 2
# 1 + 1 = 2
# 2 * (2 + 3) = 10
# 1.2 / 0.3 = 4.0
# 5 / 2 = 2

#functions
def square(number):
 sqr_num = number **2
 return sqr_num
 
input_num = 5
output_num = square(input_num)
print "print output", output_num 

#function morethan one input
def returnDifference(n1, n2):
 """Return the difference between two numbers.
 Subtracts n2 from n1."""
 return n1 - n2
print "print output", returnDifference(1,1)
 
def add_two_numbers(num1, num2):
 sum = num1 + num2
 return sum
print "print output", add_two_numbers(1,1)
print "print output", add_two_numbers(1,2) 

#loop
n = 1
while (n < 5):
 print "n =", n
 n = n +1
 print "Loop finished "
 
for n in range(1, 5):
 print"n =", n
 print "Loop finished " 
 
for i in range(0, 4):
 if i == 2:
    break
 print i
print "Finished with i = ", str(i) 

phrase = "it marks the spot"
for letter in phrase:
  if letter == "ks":
    print "yes ks" 
  break
else:
  print "There was no 'X' in the phrase"

tries = 0
while tries < 3:
 password = raw_input("Password: ")
 if password == "ednalan":
     break
 else:
     tries = tries +1
else:
     print "Suspicious activity. The authorities have been alerted."

total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print ("Inside the function local total : ", total)
   return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )  
#-------------------------------------------------------------------
def add_two_numbers(num1, num2):
    sum = num1 + num2
    return sum
    print(add_two_numbers(1,1)) #2
#---------------------------------------------------------------------
n = 1
while (n < 5):
  print("n =", n)
  n = n + 1
print("Loop finished")    
#---------------------------------------------------------------------
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
   i -= 1
   sum = sum + numbers[i]
print "The sum is: ", sum
#---------------------------------------------------------------------
import random
while (True):
   val = random.randint(1, 30)
   print val, # 14 14 30 16 16 20 23 15 17 22
   if (val ==  22):
      break
#---------------------------------------------------------------------
import random
num = 0
while (num < 1000):
   num = num + 1
   if (num % 2) == 0:
      continue
   print num,   
#---------------------------------------------------------------------
import random as rnd
for i in range(10):
   print rnd.randint(1, 10),    # 1 2 5 10 10 8 2 9 7 2

def root(x):
   return x * x
#---------------------------------------------------------------------
def root(x):
   return x * x
a = root(2)
b = root(15)
print a, b  
#---------------------------------------------------------------------
x = 15
def function():
   global x
   x = 45
function()
print x # 45
#---------------------------------------------------------------------
print 4 in (2, 3, 5, 6)
for i in range(25):
   print i, # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#---------------------------------------------------------------------
def gen():
   x = 11
   yield x
it = gen()
print it.next() # 11
#---------------------------------------------------------------------
def showModuleName():
    print __doc__
def getModuleFile():
   return __file__
a = showModuleName()
b = getModuleFile()
print a, b
#---------------------------------------------------------------------
def f():
    """This function prints a message """
    print "Today it is a cloudy day"
print isinstance(f, object) # True
print id(f) # 3077407212
print f.func_doc # This function prints a message 
print f.func_name # f
#---------------------------------------------------------------------
from math import sqrt
def cube(x):
    return x * x * x     
print abs(-1)
print cube(9)
print sqrt(81)
#---------------------------------------------------------------------
def showMessage(msg):
    print msg
def cube(x):
    return x * x * x   
x = cube(3)    
print x # 27
showMessage("Computation finished.") # Computation finished.
print showMessage("Ready.") # Ready.
#---------------------------------------------------------------------
n = [1, 2, 3, 4, 5]
def stats(x):
    mx = max(x)
    mn = min(x)
    ln = len(x)
    sm = sum(x)
    return mx, mn, ln, sm    
mx, mn, ln, sm = stats(n)
print stats(n) # (5, 1, 5, 15)
print mx, mn, ln, sm # 5 1 5 15
#---------------------------------------------------------------------
def C2F(c):
    return c * 9/5 + 32
print C2F(100) # 212
print C2F(0) # 32
print C2F(30) # 86
#---------------------------------------------------------------------
def power(x, y=2):
    r = 1
    for i in range(y):
       r = r * x
    return r
print power(3) # 9
print power(3, 3) #27
print power(5, 5) # 3125
#---------------------------------------------------------------------
def display(name, age, sex):
   print "Name: ", name
   print "Age: ", age
   print "Sex: ", sex
display("Lary", 43, "M") # Name:  Lary Age:  43 Sex:  M
display("Joan", 24, "F") # Name:  Joan Age:  24 Sex:  F


Monday, May 1, 2017

Create Custom Shortcode in WordPress Post, Page and Plugin

Create Custom Shortcode in WordPress Post, Page and Plugin

Edit current theme's function.php add this code


function recent_posts_func( $atts, $content = NULL ){
    $content = $content?$content:'Latest Posts';
    $a = shortcode_atts(
        array(
            'posts'=>5
        ),
        $atts
    );
    $args = array('numberposts'=>$a['posts']);
    $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
    echo '<div class="recent-posts">';
    echo '<h1>'.$content.'</h1>';
    foreach($recent_posts as $post){
    ?>
    <div class="updated"><p><?php echo $post['post_title']; ?>. <a href="<?php echo get_permalink($post["ID"]); ?>"><span>Show Details</span>.</a></p></div>
    <?php
    }
    echo '</div>';
}
add_shortcode( 'latestposts', 'recent_posts_func' );

Shortcode content view:

Insert the shortcode through the WordPress admin panel editor, use the below code.

[latestposts posts="2"]Recent Posts[/latestposts]

Sunday, April 30, 2017

WordPress – Adding custom fields to the post

WordPress – Adding custom fields to the post

This extra custom fields data is known as meta-data. Meta data allow you to add some additional data to the post.

Edit current theme's functions.php below code 
/*
* Add the Custom Meta Box
*/

function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box', // $id
        'Custom Meta Box', // $title 
        'show_custom_meta_box', // $callback
        'post', // $page
        'normal', // $context
        'high' // $priority
    ); 
}
add_action('add_meta_boxes', 'add_custom_meta_box');
// Custom meta fields array
$prefix = 'custom_';
$custom_meta_fields = array(
    array(
        'label'=> 'Author Name',
        'desc'  => 'Enter post author name to be displayed',
        'id'    => $prefix.'author_name',
        'type'  => 'text',
    ),
 array(
  'label'=> 'Photo',
        'desc'  => 'Enter url author photo',
        'id'    => $prefix.'photo_author',
        'type'  => 'text'
    )
);

// The callback function
function show_custom_meta_box() {

    global $custom_meta_fields, $post;
    
    // Use nonce for verification
    echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
     
    // Begin the field table and loop
    echo '<table class="form-table">';
    
    foreach ($custom_meta_fields as $field) {
        // get value of this field if it exists for this post
        $meta = get_post_meta($post->ID, $field['id'], true);
        // begin a table row with
        echo '<tr>
                <th><label for="'.$field['id'].'">'.$field['label'].'</label></th>
                <td>';
                switch($field['type']) {
                    // text field
                    case 'text':
                        echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
                            <br /><span class="description">'.$field['desc'].'</span>';
                    break;
nbsp;               }
        echo '</td></tr>';
    }
    
    echo '</table>';
    
}

// Save the custom meta data
function save_custom_meta($post_id) {

    global $custom_meta_fields;
     
    // verify nonce
    if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) 
        return $post_id;
        
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
        
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
        } elseif (!current_user_can('edit_post', $post_id)) {
            return $post_id;
    }
     
    // loop through fields and save the data
    foreach ($custom_meta_fields as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}
add_action('save_post', 'save_custom_meta');

Go to the post adding page and you can see the custom meta box and custom post fields under the post content editor.

Display the Custom Field Value

Edit current theme's single.php and add this code below


<?php 
    // Get the post meta data
    $meta = get_post_meta( get_the_ID() );
    
    // Get custom meta value
    $post_author_name = $meta['custom_author_name'][0];
    $post_photo_author = $meta['custom_photo_author'][0];
?>
<p>Author: <?php echo $post_author_name; ?> </p>
<p>Photo: <img src="<?php echo $post_photo_author; ?>"/> </p>

How to Create a Custom WordPress Widget

How to Create a Custom WordPress Widget

Add this code to your themes or functions.php
<?php
// Creating the widget 
class wpb_widget extends WP_Widget {

function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget', 

// Widget name will appear in UI
__('Simple Widget', 'wpb_widget_domain'), 

// Widget description
array( 'description' => __( 'Simple widget', 'wpb_widget_domain' ), ) 
);
}

// Creating widget front-end
// This is where the action happens
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];

// This is where you run the code and display the output
echo __( 'Hello, World!', 'wpb_widget_domain' );
echo $args['after_widget'];
}
  
// Widget Backend 
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'wpb_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php 
}
 
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class wpb_widget ends here

// Register and load the widget
function wpb_load_widget() {
 register_widget( 'wpb_widget' );
}
add_action( 'widgets_init', 'wpb_load_widget' );

PayPal Payment Gateway Integration in CodeIgniter

PayPal Payment Gateway Integration in CodeIgniter

We’ll create two tables called products and payments.

Products table


CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `price` float(10,2) NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1',
 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

payments


CREATE TABLE `payments` (
 `payment_id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `product_id` int(11) NOT NULL,
 `txn_id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_gross` float(10,2) NOT NULL,
 `currency_code` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
 `payer_email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `payment_status` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`payment_id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Controller

We’ll create two controllers Products and Paypal

Products:

This controller has two methods, index(), and buy(). index()


<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller
{
    function  __construct() {
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('product');
    }
    
    function index(){
        $data = array();
        //get products data from database
        $data['products'] = $this->product->getRows();
        //pass the products data to view
        $this->load->view('products/index', $data);
    }
    
    function buy($id){
        //Set variables for paypal form
        $returnURL = base_url().'paypal/success'; //payment success url
        $cancelURL = base_url().'paypal/cancel'; //payment cancel url
        $notifyURL = base_url().'paypal/ipn'; //ipn url
        //get particular product data
        $product = $this->product->getRows($id);
        $userID = 1; //current user id
        $logo = base_url().'assets/images/logo.png';
        
        $this->paypal_lib->add_field('return', $returnURL);
        $this->paypal_lib->add_field('cancel_return', $cancelURL);
        $this->paypal_lib->add_field('notify_url', $notifyURL);
        $this->paypal_lib->add_field('item_name', $product['name']);
        $this->paypal_lib->add_field('custom', $userID);
        $this->paypal_lib->add_field('item_number',  $product['id']);
        $this->paypal_lib->add_field('amount',  $product['price']);        
        $this->paypal_lib->image($logo);
        
        $this->paypal_lib->paypal_auto_form();
    }
}

Paypal: controller

This controller has three methods, success(), cancel(), and ipn(). success()

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Paypal extends CI_Controller 
{
     function  __construct(){
        parent::__construct();
        $this->load->library('paypal_lib');
        $this->load->model('product');
     }
     
     function success(){
        //get the transaction data
        $paypalInfo = $this->input->get();
          
        $data['item_number'] = $paypalInfo['item_number']; 
        $data['txn_id'] = $paypalInfo["tx"];
        $data['payment_amt'] = $paypalInfo["amt"];
        $data['currency_code'] = $paypalInfo["cc"];
        $data['status'] = $paypalInfo["st"];
        
        //pass the transaction data to view
        $this->load->view('paypal/success', $data);
     }
     
     function cancel(){
        $this->load->view('paypal/cancel');
     }
     
     function ipn(){
        //paypal return transaction details array
        $paypalInfo    = $this->input->post();

        $data['user_id'] = $paypalInfo['custom'];
        $data['product_id']    = $paypalInfo["item_number"];
        $data['txn_id']    = $paypalInfo["txn_id"];
        $data['payment_gross'] = $paypalInfo["mc_gross"];
        $data['currency_code'] = $paypalInfo["mc_currency"];
        $data['payer_email'] = $paypalInfo["payer_email"];
        $data['payment_status']    = $paypalInfo["payment_status"];

        $paypalURL = $this->paypal_lib->paypal_url;        
        $result    = $this->paypal_lib->curlPost($paypalURL,$paypalInfo);
        
        //check whether the payment is verified
        if(preg_match("/VERIFIED/i",$result)){
            //insert the transaction data into the database
            $this->product->insertTransaction($data);
        }
    }
}

Model (Product) Creation

Product model has two methods, getRows() and insertTransaction(). getRows()
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Product extends CI_Model{
    //get and return product rows
    public function getRows($id = ''){
        $this->db->select('id,name,image,price');
        $this->db->from('products');
        if($id){
            $this->db->where('id',$id);
            $query = $this->db->get();
            $result = $query->row_array();
        }else{
            $this->db->order_by('name','asc');
            $query = $this->db->get();
            $result = $query->result_array();
        }
        return !empty($result)?$result:false;
    }
    //insert transaction data
    public function insertTransaction($data = array()){
        $insert = $this->db->insert('payments',$data);
        return $insert?true:false;
    }
}
View Creation

Into the views directory, we’ll create two folders called products and paypal. products/ holds the view file of the Products controller and paypal/ holds the view files of Paypal controller.

products:
This directory has only one view file (index.php). This file holds the HTML for all the products listing.
<div class="row">
    <?php if(!empty($products)): foreach($products as $product): ?>
    <div class="thumbnail">
        <img src="<?php echo base_url().'assets/images/'.$product['image']; ?>" alt="">
        <div class="caption">
            <h4 class="pull-right">$<?php echo $product['price']; ?> USD</h4>
            <h4><a href="javascript:void(0);"><?php echo $product['name']; ?></a></h4>
        </div>
        <a href="<?php echo base_url().'products/buy/'.$product['id']; ?>"><img src="<?php echo base_url(); ?>assets/images/x-click-but01.gif" style="width: 70px;"></a>
    </div>
    <?php endforeach; endif; ?>
</div>

paypal:
This directory has two view file, success.php and cancel.php.
The success.php file holds the HTML for displaying the transaction success notification.
<div>
    <h2>Dear Member</h2>
    <span>Your payment was successful, thank you for purchase.</span><br/>
    <span>Item Number : 
        <strong><?php echo $item_number; ?></strong>
    </span><br/>
    <span>TXN ID : 
        <strong><?php echo $txn_id; ?></strong>
    </span><br/>
    <span>Amount Paid : 
        <strong>$<?php echo $payment_amt.' '.$currency_code; ?></strong>
    </span><br/>
    <span>Payment Status : 
        <strong><?php echo $status; ?></strong>
    </span><br/>
</div>
The cancel.php file holds the HTML for displaying the transaction cancel notification.
<div>
    <h3>Dear Member</h3>
    <p>We are sorry! Your last transaction was cancelled.</p>
</div>

paypal_lib.php file will be placed in the application/libraries/ directory and paypallib_config.php file will be placed in the application/config/ directory.

Paypal_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); 
class paypal_lib {
 var $last_error;   // holds the last error encountered
 var $ipn_log;    // bool: log IPN results to text file?
 var $ipn_log_file;   // filename of the IPN log
 var $ipn_response;   // holds the IPN response from paypal 
 var $ipn_data = array(); // array contains the POST values for IPN
 var $fields = array();  // array holds the fields to submit to paypal
 var $submit_btn = '';  // Image/Form button
 var $button_path = '';  // The path of the buttons
 
 var $CI;
 
 function __construct()
 {
  $this->CI =& get_instance();
  $this->CI->load->helper('url');
  $this->CI->load->helper('form');
  $this->CI->load->config('paypallib_config');
  
  $sanbox = $this->CI->config->item('sandbox');
  $this->paypal_url = ($sanbox == TRUE)?'https://www.sandbox.paypal.com/cgi-bin/webscr':'https://www.paypal.com/cgi-bin/webscr';
                
  $this->last_error = '';
  $this->ipn_response = '';
  $this->ipn_log_file = $this->CI->config->item('paypal_lib_ipn_log_file');
  $this->ipn_log = $this->CI->config->item('paypal_lib_ipn_log'); 
  
  $this->button_path = $this->CI->config->item('paypal_lib_button_path');
  
  // populate $fields array with a few default values.  See the paypal
  // documentation for a list of fields and their data types. These defaul
  // values can be overwritten by the calling script.
  $businessEmail = $this->CI->config->item('business');
  $this->add_field('business',$businessEmail);
  $this->add_field('rm','2');     // Return method = POST
  $this->add_field('cmd','_xclick');
  
  $this->add_field('currency_code', $this->CI->config->item('paypal_lib_currency_code'));
      $this->add_field('quantity', '1');
  $this->button('Pay Now!');
 }
 function button($value)
 {
  // changes the default caption of the submit button
  $this->submit_btn = form_submit('pp_submit', $value);
 }
 function image($file)
 {
  $this->submit_btn = '<input type="image" name="add" src="' . site_url($this->button_path .'/'. $file) . '" border="0" />';
 }
 function add_field($field, $value) 
 {
  // adds a key=>value pair to the fields array, which is what will be 
  // sent to paypal as POST variables.  If the value is already in the 
  // array, it will be overwritten.
  $this->fields[$field] = $value;
 }
 function paypal_auto_form() 
 {
  // this function actually generates an entire HTML page consisting of
  // a form with hidden elements which is submitted to paypal via the 
  // BODY element's onLoad attribute.  We do this so that you can validate
  // any POST vars from you custom form before submitting to paypal.  So 
  // basically, you'll have your own form which is submitted to your script
  // to validate the data, which in turn calls this function to create
  // another hidden form and submit to paypal.
  $this->button('Click here if you\'re not automatically redirected...');
  echo '<html>' . "\n";
  echo '<head><title>Processing Payment...</title></head>' . "\n";
  echo '<body style="text-align:center;" onLoad="document.forms[\'paypal_auto_form\'].submit();">' . "\n";
  echo '<p style="text-align:center;">Please wait, your order is being processed and you will be redirected to the paypal website.</p>' . "\n";
  echo $this->paypal_form('paypal_auto_form');
  echo '</body></html>';
 }
 function paypal_form($form_name='paypal_form') 
 {
  $str = '';
  $str .= '<form method="post" action="'.$this->paypal_url.'" name="'.$form_name.'"/>' . "\n";
  foreach ($this->fields as $name => $value)
   $str .= form_hidden($name, $value) . "\n";
  $str .= '<p>'. $this->submit_btn . '</p>';
  $str .= form_close() . "\n";
  return $str;
 }
 
 function validate_ipn()
 {
  // parse the paypal URL
  $url_parsed = parse_url($this->paypal_url);    
  // generate the post string from the _POST vars aswell as load the
  // _POST vars into an arry so we can play with them from the calling
  // script.
  $post_string = '';  
  if ($this->CI->input->post())
  {
   foreach ($this->CI->input->post() as $field=>$value)
   { 
    $this->ipn_data[$field] = $value;
    $post_string .= $field.'='.urlencode(stripslashes($value)).'&'; 
   }
  }
  
  $post_string.="cmd=_notify-validate"; // append ipn command
  // open the connection to paypal
  $fp = fsockopen($url_parsed['host'],"80",$err_num,$err_str,30); 
  if(!$fp)
  {
   // could not open the connection.  If loggin is on, the error message
   // will be in the log.
   $this->last_error = "fsockopen error no. $errnum: $errstr";
   $this->log_ipn_results(false);   
   return false;
  } 
  else
  { 
   // Post the data back to paypal
   fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n"); 
   fputs($fp, "Host: $url_parsed[host]\r\n"); 
   fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); 
   fputs($fp, "Content-length: ".strlen($post_string)."\r\n"); 
   fputs($fp, "Connection: close\r\n\r\n"); 
   fputs($fp, $post_string . "\r\n\r\n"); 
   // loop through the response from the server and append to variable
   while(!feof($fp))
    $this->ipn_response .= fgets($fp, 1024); 
   fclose($fp); // close connection
  }
  if (preg_match("/VERIFIED/",$this->ipn_response))
  {
   // Valid IPN transaction.
   $this->log_ipn_results(true);
   return true;   
  } 
  else 
  {
   // Invalid IPN transaction.  Check the log for details.
   $this->last_error = 'IPN Validation Failed.';
   $this->log_ipn_results(false); 
   return false;
  }
 }
 function log_ipn_results($success) 
 {
  if (!$this->ipn_log) return;  // is logging turned off?
  // Timestamp
  $text = '['.date('m/d/Y g:i A').'] - '; 
  // Success or failure being logged?
  if ($success) $text .= "SUCCESS!\n";
  else $text .= 'FAIL: '.$this->last_error."\n";
  // Log the POST variables
  $text .= "IPN POST Vars from Paypal:\n";
  foreach ($this->ipn_data as $key=>$value)
   $text .= "$key=$value, ";
  // Log the response from the paypal server
  $text .= "\nIPN Response from Paypal Server:\n ".$this->ipn_response;
  // Write to log
  $fp=fopen($this->ipn_log_file,'a');
  fwrite($fp, $text . "\n\n"); 
  fclose($fp);  // close file
 }
 function dump() 
 {
  // Used for debugging, this function will output all the field/value pairs
  // that are currently defined in the instance of the class using the
  // add_field() function.
  ksort($this->fields);
  echo '<h2>ppal->dump() Output:</h2>' . "\n";
  echo '<code style="font: 12px Monaco, \'Courier New\', Verdana, Sans-serif;  background: #f9f9f9; border: 1px solid #D0D0D0; color: #002166; display: block; margin: 14px 0; padding: 12px 10px;">' . "\n";
  foreach ($this->fields as $key => $value) echo '<strong>'. $key .'</strong>: '. urldecode($value) .'<br/>';
  echo "</code>\n";
 }
 
 
 function curlPost($paypalurl,$paypalreturnarr)
 {
  
  $req = 'cmd=_notify-validate';
  foreach($paypalreturnarr as $key => $value) 
  {
   $value = urlencode(stripslashes($value));
   $req .= "&$key=$value";
  }
   
  $ipnsiteurl=$paypalurl;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $ipnsiteurl);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
  $result = curl_exec($ch);
  curl_close($ch);
 
  return $result;
 }
}
?>
paypallib_config.php
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// ------------------------------------------------------------------------
// Paypal IPN Class
// ------------------------------------------------------------------------
// Use PayPal on Sandbox or Live
$config['sandbox'] = TRUE; // FALSE for live environment
// PayPal Business Email ID
$config['business'] = 'InsertPayPalBusinessEmail';
// If (and where) to log ipn to file
$config['paypal_lib_ipn_log_file'] = BASEPATH . 'logs/paypal_ipn.log';
$config['paypal_lib_ipn_log'] = TRUE;
// Where are the buttons located at 
$config['paypal_lib_button_path'] = 'buttons';
// What is the default currency?
$config['paypal_lib_currency_code'] = 'USD';
?>


Test PayPal Transaction

Open the Products controller (http://localhost/codeigniter/products)

Friday, April 28, 2017

Back to Top Button using jQuery and CSS

Back to Top Button using jQuery and CSS
<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Back to Top Button using jQuery and CSS</title>

</head>
<body>
<style type="text/css">
/* page text content css */
h1{font-size:45px;text-align:center; text-decoration:underline;}
h3{font-size:40px;color:#FA0530}
p{font-size:40px;}

/* BackToTop button css */
#scroll {
position:fixed;
right:10px;
bottom:10px;
cursor:pointer;
width:50px;
height:50px;
background-color:#3498db;
text-indent:-9999px;
display:none;
-webkit-border-radius:60px;
-moz-border-radius:60px;
border-radius:60px
}
#scroll span {
position:absolute;
top:50%;
left:50%;
margin-left:-8px;
margin-top:-12px;
height:0;
width:0;
border:8px solid transparent;
border-bottom-color:#ffffff
}
#scroll:hover {
background-color:#e74c3c;
opacity:1;filter:"alpha(opacity=100)";
-ms-filter:"alpha(opacity=100)";}
</style>
<div class="row">
        <div class="col-lg-12">
            <div >
                <!-- BackToTop Button -->
<a href="#" id="scroll" title="Scroll to Top" style="display: none;">Top<span></span></a>

<h1>jQuery Back to Top Button</h1>
<h3>Scroll down the page, the BackToTop button would be appear at the right side corner. Once you click on this button, the page would be scrolling up to the top.</h3>
<!-- Demo Text -->
<p>Cras dui massa, dapibus eget nulla gravida, tempus vestibulum neque. Vestibulum ut euismod tellus, id facilisis velit. Sed vitae nunc at ex lobortis sagittis sit amet a ex. Mauris mollis tellus et tortor euismod scelerisque. In non facilisis lorem, non egestas nisl. Suspendisse potenti. Nunc in enim sed ipsum volutpat ultricies. Curabitur porta eros eget lacus maximus iaculis. Nulla ac sapien fermentum, lobortis risus eget, pellentesque eros. Aliquam erat volutpat. Vestibulum nulla erat, pulvinar nec condimentum sed, faucibus at velit.</p>

<p>Mauris eleifend facilisis pharetra. Nullam vestibulum malesuada dictum. Nulla blandit sit amet massa nec tempor. Vestibulum sit amet urna ut eros placerat vehicula in id felis. Curabitur quis imperdiet urna. Sed dictum suscipit velit, eget bibendum lectus fermentum sed. Nunc eget quam enim. Vivamus eget nisi non erat rhoncus accumsan vel vitae neque. Nam cursus felis sed elementum consectetur. Vivamus mattis, felis vel eleifend luctus, nisl ante dictum massa, sit amet semper lorem odio consectetur risus.</p>

<p>Aliquam erat volutpat. Cras consequat lacus nec enim imperdiet convallis. Quisque tincidunt et mi quis euismod. Aenean faucibus tincidunt libero, vitae vulputate ante commodo vel. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque laoreet est eu lectus aliquam iaculis a nec enim. Etiam aliquet mi ac lectus laoreet luctus. Nulla quis ante nisl. Ut sit amet nibh non odio suscipit posuere. Donec ac tellus quis ante efficitur tincidunt et sit amet neque. Integer aliquet neque eget tellus luctus gravida. Sed maximus lobortis cursus. Praesent et felis ante. Mauris massa justo, tristique at lacus ut, consectetur ultrices purus. Vivamus et ex nec sem tempor tincidunt. Suspendisse elementum sem erat, sed euismod felis sodales et.</p>

<p>Vivamus ut massa quis risus bibendum condimentum. Nunc commodo libero eu tincidunt facilisis. Morbi ut tellus eu lacus interdum egestas. Pellentesque faucibus porttitor lacus, vitae efficitur nulla suscipit sed. Aenean dapibus magna quis dui blandit, nec aliquam tellus consectetur. Curabitur porttitor lacus nec quam finibus, quis iaculis ante sodales. Ut egestas varius arcu, id condimentum lorem congue a. Duis in tellus eget leo lobortis placerat vel sed tortor. Curabitur eu risus mi.</p>

<p>Proin non odio laoreet, sollicitudin nulla quis, laoreet velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi vel tellus a libero venenatis pharetra. Praesent ac bibendum tortor. In varius metus quis vehicula auctor. Nullam viverra id odio vel convallis. Sed tortor est, aliquam quis suscipit ac, tempus nec purus. Curabitur euismod congue dui, id rutrum quam dictum sit amet. In a metus maximus, condimentum lorem volutpat, feugiat lectus.</p>
            </div>
        </div>
    </div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){ 
 $(window).scroll(function(){ 
  if ($(this).scrollTop() > 100) { 
   $('#scroll').fadeIn(); 
  } else { 
   $('#scroll').fadeOut(); 
  } 
 }); 
 $('#scroll').click(function(){ 
  $("html, body").animate({ scrollTop: 0 }, 600); 
  return false; 
 }); 
});
</script>
</body>
</html>

Related Post