Tuesday 25 August 2015

Tools for Testing WordPress Site’s Performance and Speed

Have you ever sat and waited for a slow loading website? Chances are, instead of waiting precious seconds for the site to load, you opted for the Back button. In other words, the internet operates a feverish pace, and if your site can’t keep up you run the risk of losing customers, visitors and subscribers.
Fast sites have better user engagement, conversion rates, and perhaps even search engine rankings – it’s time for you to get on board. In this post I explore five tools for testing your WordPress site’s performance and speed, so that you can make the necessary changes today.

Why Does Your Site Load Slowly?

There are multiple reasons your site could be performing worse than usual. Loading speeds are going to vary site by site, but there are a few factors that trip up most sites.
For WordPress websites, the most common causes of page loading slow-downs are bloated plugins, having a poorly coded theme, big image files, and/or having poor hosting not suited to your website. Below we’ll show you how to fix these common issues. However, before you jump into optimizing your website, you need to see how fast it’s running in the first place.

Top Tools For Testing Your Site’s Performance

The following tools will give you a complete picture of your website’s performance. You can use a single tool, or use them all in conjunction to cross-reference website data.

1. Google PageSpeed Insights


PageSpeed Insights is a brainchild of Google. This nifty web app measures your site’s performance across multiple devices, including desktop and mobile browsers. This is useful if your visitors are accessing your site from a variety of screen sizes and devices.

2. Pingdom

  Pingdom is a free tool that gives you full-site performance information including load time, page size, as well as a detailed analysis of each page on your website. Best of all, this app saves your performance history, so you can track if your efforts to improve loading times are working.

3. GTmetrix

 

The report that GTmetrix generates will show you a complete history of the website’s loading speeds, as well as a detailed report that suggests ways to improve the performance of your website. Beyond the initial page analysis tools, this web tool also has a video playback feature that enables you to see where the loading speed bottlenecks occur.

4. WebPagetest

WebPagetest gives you your site’s loading speed and a grade breakdown of your site’s performance. It’s unique in that it allows you to select a country to view your report from, so you can see how your site performs across the world. This is useful if you have a large overseas user base.

5. YSlow Browser Plugin

 

YSlow is a browser plugin that lets you track the performance of any site you’re currently visiting. It doesn’t give you the actual load time, but it does break down over 20 different performance cues. This can help you compare other competitors site’s within your niche to see how your site stands up.

Options for Speeding Up Your WordPress Site

Once you have a clear idea of how your site is performing, you can begin to improve it. Below you’ll find a few of the most common slow loading page culprits and what you can do to fix them.

Specialized Hosting

The cheapest hosting solution is never the best choice for high website performance. Cheaper hosting usually doesn’t have the dedicated bandwidth to cater to every detail of your WordPress site (this is one of the ways they keep their costs in check to offer you those crazy low prices).

Consider Uninstalling Certain Plugins

It can be very tempting to add one more feature to your website through the use of a plugin; after all, there are over 30,000 plugins available from the WordPress Plugin Directory alone.
If you are considering installing a plugin, make sure it’s high quality, as poorly coded plugins could be slowing down your site. When selecting a plugin, make sure it has a high rating, a large number of downloads and has been updated recently.
One way to see which plugins are affecting your site’s performance is to use a tool called P3 Plugin Profiler. You could go through every plugin on your site, de-activate and re-active each one, while doing site loading tests – or you could use this plugin. P3 Plugin Profiler will give you a detailed breakdown of your plugin’s usage and help you determine which plugins are causing the most problems.

Having A Poorly Coded Theme

Be aware that poorly coded and low-quality themes can drastically affect your site’s performance. Even if you’ve paid a premium price for a theme, this doesn’t guarantee it’s going to have high-quality code.
A good benchmark is to test your current theme, or a theme you’re thinking about buying, against the native WordPress theme that’s present after a fresh installation.

Compressing Images

High-quality images are crucial to helping your content and website stand out, but don’t let them impact your site’s performance. You can compress your images without losing quality, which will keep your site running fast. The following plugins will compress anything that’s in the Media Library section of your website.
If you don’t want to install a plugin then another option is to use an online image compression tool, such as TinyPNG or Kraken, before uploading the image to your site.

Use a Caching Plugin

Since WordPress sites have to make regular database requests, a caching plugin reduces these requests by generating a static HTML page to display instead. Caching plugins can help your site handle larger amounts of traffic, and also compress and optimize other areas of your site.Two of the most commonly used caching plugins are WP Super Cache and W3 Total Cache. It’s difficult to pick one over the other, so take a look yourself and pick whichever one that takes your fancy.

Continued Site Maintenance

If you want your site to remain fast then you’ll need to maintain it on a regular basis. Continued maintenance on your site includes dealing with comment spam, fixing any broken links and pages, and optimizing your database with a plugin like WP-DBManager.  This will help keep your site’s performance high, so you don’t see a decrease in your newly upgraded site you’ve worked so hard for.

Conclusion

Having a high performing website with fast loading speeds will only become most important as time goes on. Luckily, with a suite of free online tools and WordPress plugins, you can find the trouble spots and fix them without too much work. How do you keep your site lean and running fast? Any plugin mentions we missed? I’d love to hear about them!

Friday 21 August 2015

Create / Read / Erase Cookie using Javascript

These are the three javascript function.

  1.     createCookie: Using this function you can create cookie 

  2.     readCookie: This function is used to read cookie. 

  3.     eraseCookie: Use this function to erase any existing cookie.


    <style type="text/css">
    function createCookie(name, value, days) {
        var expires;

        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        } else {
            expires = "";
        }
        document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
    }

    function readCookie(name) {
        var nameEQ = escape(name) + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name, "", -1);
    }
    </script>

    If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

     

How To Generate Password Using PHP

When we are building any application from where authentication required, then we need to generate strong password. This article will explain how we can generate password using PHP. Here we have just created one function “generateStrongPassword” having 2 parameters one is length and second is strength. Using these parameters we can customize the generated password.

<?php
function generateStrongPassword($length=9, $strength=4) {
 $vowels = 'aeuy';
 $string = 'bcdfghjmnpqrstvz';
 if ($strength & 1) {
 $string .= 'BCDFGHJLMNPQRSTVWXZ';
 }
 if ($strength & 2) {
 $vowels .= "AEUY";
 }
 if ($strength & 4) {
 $string .= '23456789';
 }
 if ($strength & 8) {
 $string .= '@#$!';
 }

 $password = '';
 $alt = time() % 2;
 for ($i = 0; $i < $length; $i++) {
 if ($alt == 1) {
 $password .= $string[(rand() % strlen($string))];
 $alt = 0;
 } else {
 $password .= $vowels[(rand() % strlen($vowels))];
 $alt = 1;
 }
 }
 return $password;
}
?>

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries. 

How To Create Parent Child Category Tree Using PHP & MySQLi

In this tutorial we are going to explain how to create nth level category tree using PHP and MySQLi. We have write a very simple php function and call recursivily.

 

First we have created a database table with parent child mapping of categories:


 CREATE TABLE `tbl_categories` (
   `id` INT(11) NOT NULL AUTO_INCREMENT,
   `name` VARCHAR(100) NOT NULL DEFAULT '0',
   `parent_id` INT(11) NOT NULL DEFAULT '0',
   PRIMARY KEY (`id`)
 )
 ENGINE=InnoDB;
 

 Insert dummy categories:

 
 INSERT INTO `tbl_categories` (`id`, `name`, `parent_id`) VALUES
(1, 'Hardware', 0),
(2, 'Software', 0),
(3, 'Movies', 0),
(4, 'Clothes', 0),
(5, 'Printers', 1),
(6, 'Monitors', 1),
(7, 'Inkjet printers', 5),
(8, 'Laserjet Printers', 5),
(9, 'LCD monitors', 6),
(10, 'TFT monitors', 6),
(11, 'Antivirus', 2),
(12, 'Action movies', 3),
(13, 'Comedy Movies', 3),
(14, 'Romantic movie', 3),
(15, 'Thriller Movies', 3),
(16, 'Mens', 4),
(17, 'Womens', 4),
(18, 'Shirts', 16),
(19, 'T-shirts', 16),
(20, 'Shirts', 16),
(21, 'Jeans', 16),
(22, 'Accessories', 16),
(23, 'Tees', 17),
(24, 'Skirts', 17),
(25, 'Leggins', 17),
(26, 'Jeans', 17),
(27, 'Accessories', 17),
(28, 'Watches', 22),
(29, 'Tie', 22),
(30, 'cufflinks', 22),
(31, 'Earrings', 27),
(32, 'Bracelets', 27),
(33, 'Necklaces', 27),
(34, 'Pendants', 27);
 

Category Parent Child Tree Function:

 <?php
function categoryParentChildTree($parent = 0, $spacing = '', $category_tree_array = '') {
    global $dbConnection;
    $parent = $dbConnection->real_escape_string($parent);
    if (!is_array($category_tree_array))
        $category_tree_array = array();

    $sqlCategory = "SELECT id,name,parent_id FROM tbl_categories WHERE parent_id = $parent ORDER BY id ASC";
    $resCategory=$dbConnection->query($sqlCategory);
   
    if ($resCategory->num_rows > 0) {
        while($rowCategories = $resCategory->fetch_assoc()) {
            $category_tree_array[] = array("id" => $rowCategories['id'], "name" => $spacing . $rowCategories['name']);
            $category_tree_array = categoryParentChildTree($rowCategories['id'], '&nbsp;&nbsp;&nbsp;&nbsp;'.$spacing . '-&nbsp;', $category_tree_array);
        }
    }
    return $category_tree_array;
}  ?>

 index.php

<?php
    require_once 'db_connection.php';
    require_once 'functions.php';
   
    $categoryList = categoryParentChildTree();
    foreach($categoryList as $key => $value){
        echo $value['name'].'<br>';
    }  ?>
 

 If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Autocomplete search using php, mysql and ajax

We know what is autocomplete in input type, that is make some predefined entered texts come under the input type box, while focusing on the input type, similarly we are searching some content from mysql database, this actually see image style search concept to suggest some data for select before we get the exact search, for that we are using this kind of search, and this is very simple to make search in php, mysql with ajax and jquery. let see it in brief.

 

as like you see in the above image, the search will be comes like that by using php, mysql and ajax with jquery.

DATABASE DETAILS

database name-->phpmvcbug

table name --> autocomplete

column names --> id, name, email


DB.PHP
<?php
$connection = mysql_connect('localhost','root','') or die(mysql_error());
$database = mysql_select_db('phpmvcbug') or die(mysql_error());
?>

the above is database file.

INDEX.PHP
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search for people" /> 
 Ex:arunkumar, shanmu, vicky<br /> 
<div id="result"></div>
</div>

just give this input type only in index page with AJAX. you can see the ajax coding below here that is also comes in index page


AJAX
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;    
});

jQuery("#result").live("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find('.name').html();
    var decoded = $("<div/>").html($name).text();
    $('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});
$('#searchid').click(function(){
    jQuery("#result").fadeIn();
});
});
</script>

the above all for make action in SEARCH page with out refreshing the page.


SEARCH.PHP
<?php
include('db.php');
if($_POST)
{
$q=$_POST['search'];
$sql_res=mysql_query("select id,name,email from autocomplete where name 
                      like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['name'];
$email=$row['email'];
$b_username='<strong>'.$q.'</strong>';
$b_email='<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="show" align="left">
<img src="author.PNG" style="width:50px; height:50px; float:left; margin-right:6px;" />
 <span class="name"><?php echo $final_username; ?></span>&nbsp;<br/> 
<?php echo $final_email; ?><br/>
</div>
<?php
}
}
?>

that's it. as like the usual fetch from database with like and here we are just adding str_ireplace, that's it. and other thinks are as like we know, that is very simple one. let's try this. and each of our entering text that wil comes as in strong letter.

 

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

File download coding using PHP and Mysql

File downloading code is the method of downloading a file from the database, how to download a file from the database, usually uploaded file are stored in the database and how we can download it. let see, using PHP code we going to download the file. so here we must have to know the upload coding. here i'm not showing upload code, here i just show you and explain you the downloading code only.

 here my database field details are,

Database name --> phpmvcbug
table name --> upload
column names --> id, name, type (3 columns)

the above is database structure.

DB.PHP

<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error());
$db=mysql_select_db("phpmvcbug",$conn);
?>

INDEX.PHP

<?php 
    include("db.php");  
    $fetc = "SELECT * FROM upload LIMIT 5";
    $result = mysql_query($fetc);
?>
<body>
<?php
while($row1=mysql_fetch_array($result))
{
    $name=$row1['name'];
    $type=$row1['type'];
    ?>
<div class="rect">
<img alt="down-icon" src="down-drop-icon.png" align="left" width="20" height="20" />
<a href="download.php?filename=<?php echo $name ;?>" >
<?php echo $name ;?></a>
</div>
<?php 
} 
?>
</body>

select * from upload table limit to show only 5 data s. and the variable $result is fetched as array in while and echo the file name. for that file name we are giving the download link, that is from download.php.


DOWNLOAD.PHP

<?php
function output_file($file, $name, $mime_type='')
{
 if(!is_readable($file)) die('File not found or inaccessible!');
 $size = filesize($file);
 $name = rawurldecode($name);
 $known_mime_types=array(
    "htm" => "text/html",
    "exe" => "application/octet-stream",
    "zip" => "application/zip",
    "doc" => "application/msword",
    "jpg" => "image/jpg",
    "php" => "text/plain",
    "xls" => "application/vnd.ms-excel",
    "ppt" => "application/vnd.ms-powerpoint",
    "gif" => "image/gif",
    "pdf" => "application/pdf",
    "txt" => "text/plain",
    "html"=> "text/html",
    "png" => "image/png",
    "jpeg"=> "image/jpg"
 );
 
 if($mime_type==''){
     $file_extension = strtolower(substr(strrchr($file,"."),1));
     if(array_key_exists($file_extension, $known_mime_types)){
        $mime_type=$known_mime_types[$file_extension];
     } else {
        $mime_type="application/force-download";
     };
 };
 
 //turn off output buffering to decrease cpu usage
 @ob_end_clean(); 
 
 // required for IE, otherwise Content-Disposition may be ignored
 if(ini_get('zlib.output_compression'))
 ini_set('zlib.output_compression', 'Off');
 header('Content-Type: ' . $mime_type);
 header('Content-Disposition: attachment; filename="'.$name.'"');
 header("Content-Transfer-Encoding: binary");
 header('Accept-Ranges: bytes');
 
 // multipart-download and download resuming support
 if(isset($_SERVER['HTTP_RANGE']))
 {
    list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
    list($range) = explode(",",$range,2);
    list($range, $range_end) = explode("-", $range);
    $range=intval($range);
    if(!$range_end) {
        $range_end=$size-1;
    } else {
        $range_end=intval($range_end);
    }

    $new_length = $range_end-$range+1;
    header("HTTP/1.1 206 Partial Content");
    header("Content-Length: $new_length");
    header("Content-Range: bytes $range-$range_end/$size");
 } else {
    $new_length=$size;
    header("Content-Length: ".$size);
 }
 
 /* Will output the file itself */
 $chunksize = 1*(1024*1024); //you may want to change this
 $bytes_send = 0;
 if ($file = fopen($file, 'r'))
 {
    if(isset($_SERVER['HTTP_RANGE']))
    fseek($file, $range);
 
    while(!feof($file) && 
        (!connection_aborted()) && 
        ($bytes_send<$new_length)
          )
    {
        $buffer = fread($file, $chunksize);
        echo($buffer); 
        flush();
        $bytes_send += strlen($buffer);
    }
 fclose($file);
 } else
 //If no permissiion
 die('Error - can not open file.');
 //die
die();
}
//Set the time out
set_time_limit(0);

//path to the file
$file_path='files/'.$_REQUEST['filename'];


//Call the download function with file path,file name and file type
output_file($file_path, ''.$_REQUEST['filename'].'', 'text/plain');
?>

look at the highlighted part in the above coding. from the folder name files the files are already stored and we are retrieving that.

types as store in Database


    "htm" => "text/html",
    "exe" => "application/octet-stream",
    "zip" => "application/zip",
    "doc" => "application/msword",
    "jpg" => "image/jpg",
    "php" => "text/plain",
    "xls" => "application/vnd.ms-excel",
    "ppt" => "application/vnd.ms-powerpoint",
    "gif" => "image/gif",
    "pdf" => "application/pdf",
    "txt" => "text/plain",
    "html"=> "text/html",
    "png" => "image/png",
    "jpeg"=> "image/jpg"

if the file name is extended with above all extensions. the type stored in database must by like that the above. that is important.

 

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.

Username live availability Check using php and Ajax

Username live availability is one of the most important thing the database field, why because mostly we have to different kind of username and unique name for all users. then only we can identify the individual user, so for here we are going to check the database field for already existing username availability. so here we are using php fetch coding and AJAX live check without refreshing of the page.

DATABASE

<?php
$conn = mysql_connect("localhost","root","") or die("Database not connected");
$db=mysql_select_db("phpmvcbug", $conn) or die("Database not connected");
?>

database name is --> mvcbugase

table name is --> usernames

Check Database coding

<?php
include('db.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$sql = mysql_query("select id from usernames where username='$username'");
if(mysql_num_rows($sql))
{
echo '<STRONG>'.$username.'</STRONG> is already in use.';
}
else
{
echo 'OK';
}
}
?>

AJAX

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#username").change(function() 
{ 
var username = $("#username").val();
var msgbox = $("#status");

if(username.length > 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">Checking availability...');

$.ajax({  
    type: "POST",  
    url: "ajax.php",  
    data: "username="+ username,  
    success: function(msg){  
   $("#status").ajaxComplete(function(event, request){ 
    if(msg == 'OK')
    { 
    
        $("#username").removeClass("red");
        $("#username").addClass("green");
        msgbox.html('<img src="available.png" align="absmiddle">');
    }  
    else  
    {  
         $("#username").removeClass("green");
         $("#username").addClass("red");
        msgbox.html(msg);
    }  
   
   });
   } 
   
  }); 

}
else
{
$("#username").addClass("red");
$("#status").html('<font color="#cc0000">Please nter atleast 5 letters</font>');
}
return false;
});

});
</script>

index page

<input type="text" name="username" id="username" style="margin-top:35px;" />&nbsp;
<span id="status"></span>

span id="status" is for show the result of the output.

that's it. for live availability check username using php, mysql, and Ajax. 

 

If you have any problem regarding this tutorial configuration please feel free to comment we love to answer your queries.