Sunday 17 December 2017

Disable Admin Bar in wordpress.

Paste this code in your theme’s functions.php file


add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
  show_admin_bar(false);
}
}

If you want to disable it for all users, then simply put use this code in your theme’s functions.php file



  show_admin_bar(false);

Sunday 30 July 2017

Use htmlentities with the correct characterset option

1
$value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');

Difference Between Comparison Operators in php.

If you use strpos() to determine whether a substring exists within a string (it returns FALSE

<?php
 
$authors = 'Chris & Sean';
 
if (strpos($authors, 'Chris')) {
    echo 'Chris is an author.';
} else {
    echo 'Chris is not an author.';
}
 
?>

Friday 28 July 2017

Logical Operators Example

   <?php
         $a = 42;
         $b = 0;
         
         if( $a && $b ) {
            echo "TEST1 : Both a and b are true<br/>";
         }else{
            echo "TEST1 : Either a or b is false<br/>";
         }
         
         if( $a and $b ) {
            echo "TEST2 : Both a and b are true<br/>";
         }else{
            echo "TEST2 : Either a or b is false<br/>";
         }
         
         if( $a || $b ) {
            echo "TEST3 : Either a or b is true<br/>";
         }else{
            echo "TEST3 : Both a and b are false<br/>";
         }
         
         if( $a or $b ) {
            echo "TEST4 : Either a or b is true<br/>";
         }else {
            echo "TEST4 : Both a and b are false<br/>";
         }
         
         $a = 10;
         $b = 20;
         
         if( $a ) {
            echo "TEST5 : a is true <br/>";
         }else {
            echo "TEST5 : a  is false<br/>";
         }
         
         if( $b ) {
            echo "TEST6 : b is true <br/>";
         }else {
            echo "TEST6 : b  is false<br/>";
         }
         
         if( !$a ) {
            echo "TEST7 : a is true <br/>";
         }else {
            echo "TEST7 : a  is false<br/>";
         }
         
         if( !$b ) {
            echo "TEST8 : b is true <br/>";
         }else {
            echo "TEST8 : b  is false<br/>";
         }
      ?>
 
This will produce the following result −


TEST1 : Either a or b is false
TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false
 

How to print following number table:

How to print following number table:




<table width="270px" cellspacing="0px" cellpadding="0px" border="1px">  
   <!-- cell 270px wide (8 columns x 60px) -->  
    <?php  
        //$a = 1;
      for($row=1;$row<=10;$row++)  
      {  
          echo "<tr>";
         
          for($col=1;$col<=10;$col++)  
          {  
              echo "<td>" .($col * $row). "</td>";
          }
          //$a++;
          echo "</tr>";
      }
      ?>
 </table>

Write a program to make a chess:

Write a program to make a chess:












  <table width="270px" cellspacing="0px" cellpadding="0px" border="1px">
   <!-- cell 270px wide (8 columns x 60px) -->  
      <?php  
      for($row=1;$row<=8;$row++)  
      {  
          echo "<tr>";  
          for($col=1;$col<=8;$col++)  
          {  
          $total=$row+$col;  
          if($total%2==0)  
          {  
          echo "<td height=30px width=30px bgcolor=#FFFFFF></td>";  
          }  
          else  
          {  
          echo "<td height=30px width=30px bgcolor=#000000></td>";  
          }  
          }  
          echo "</tr>";  
    }  
          ?>  
  </table>  

Program to print below format...

(1) Program to print below format
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *



<?php

   $rows=5; // number of row
      for($i=1;$i<=$rows;$i++)
        {
 
           for($j=1;$j<=$i;$j++)
              {
                echo "*";
              }
            echo "<br />";
        }




?> 





(2 ) Write a program to print the below format :
1 5 9
2 6 10
3 7 11
4 8 12



<?php

for($i=1;$i<=4;$i++)
{
 $i1=$i+4;
 $i2=$i+8;
echo $i." ".$i1." ".$i2;
echo "<br />";
}


?>
 
 
(3) Write a program for this Pattern:
 
*****
*      *
*      *
*      *
*****
 
<?php
for($i = 1; $i<=5; $i++){
            for($j = 1; $j<=5; $j++){
               if($i == 1 || $i == 5){
                   echo "*";
               }
               else if($j == 1 || $j == 5){
                   echo "*";
               }
               else {
                   echo "&nbsp;&nbsp;";
               }
               
            }
            echo "<br/>";
}
?>
 

 
 
 
 
 
 


Program to print below format..

Program to print below format.
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1





<?php
   $rows=5;  // number of row
   for($i=$rows;$i>=1;--$i)
     {
         for($j=1;$j<=$i;++$j)
         {
            echo $j;
         }
     echo "<br />";
     }
 ?>
 

Program to print the below format.

Program to print the below format
* * * * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *



<?php


   $rows=5;  // number of row enter.
   for($i=$rows;$i>=1;--$i)
     {
         for($space=0;$space<$rows-$i;++$space)
            echo "  ";
         for($j=$i;$j<=2*$i-1;++$j)
           echo "* ";
         for($j=0;$j<$i-1;++$j)
             echo "* ";
         echo "<br />";
     }



?>

Program to find year is LEAP year or not.


<?php
    $year=2017;
    if($year%4==0)
          {
            $leap="It is a leap year";
          }
      else
         {
           $leap="It is not a leap year";
        }
 ?>

Write a program to print Fibonacci series

Write a program to print Fibonacci series

<?php
$fibo=array(0,1);
$num=4;
     for($i=2;$i<=$num-1;$i++)
{
       $fibo[$i]=$fibo[$i-1]+$fibo[$i-2];
      }
?>

To check whether a number is Prime or not.

<?php

   $check=0;
   $num=$_POST['number'];
   for($i=2;$i<=($num/2);$i++)
     { 
       if($num%$i==0)
         {
          $check++;
          if($check==1)
          {
             break;
          }
         }
     }

?>

Write a program to print Reverse in php

<?php
         $rev=0;
         $num=4;
         
          while($num>=1)
                {
                  $re=$num%10;
                  $rev=$rev*10+$re;
                  $num=$num/10;
                 }

?>

Write a program to find whether a number is Armstrong or not in php.


<?php
if(isset($_POST['number']) && $_POST['number']!='') 
    {  
      
        $number = $_POST[ 'number' ];      // get the number entered by user
     
        $temp = $number;
        $sum  = 0;
     
        while($temp != 0 )
        {
            $remainder   = $temp % 10; //find reminder
            $sum         = $sum + ( $remainder * $remainder * $remainder );
            $temp        = $temp / 10;

       }
        if( $number == $sum )
        {
            echo "$number is an Armstrong Number";
        }else
        {
            echo "$number is not an Armstrong Number";
        }
    }
?>

Write a program in PHP to print Fibonacci series . 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

<?PHP 
   $first = 0;
   $second = 1;
   echo $first.'&nbsp;,';
   echo $second.'&nbsp;,';
  
  for($limit=0;$limit<10;$limit++)
   {
     $third = $first+$second;
     echo $third.'&nbsp;,';;
     $first = $second;
     $second = $third;

   
   }
?>

Write a program to print Factorial number in php.

<?php

$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
  $factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";

?>


Output
Factorial of 4 is 24

Friday 21 July 2017

Display latest comments in wordpress template.

Display latest comments for each post in WordPress

<?php 
$commentArr = array_reverse(get_approved_comments($wp_query->post->ID));
$count = 1; // number of comments
if ($commentArr) { ?>
    <h3><?php commentsNum('0 comment', '1 comment', '% comments'); ?></h3>
    <ul>
    <?php foreach ($commentArr as $comment) {
        if ($count++ <= 2) { ?>
        <li><?php comment_author_link(); ?>: <?php comment_excerpt(); ?></li>
        <?php }
    } ?>
    </ul>
<?php } else {
    echo '<p>No Comments..</p>';
} ?>

Thursday 20 July 2017

How to add facebook fun page in Blog and page.

Click "Add Widget" to post a badge on your Blogger site that links to your Facebook account.

Step 2: Place this code wherever you want the plugin to appear on your page.

<iframe src="https://www.facebook.com/plugins/follow.php?href=https%3A%2F%2Fwww.facebook.com%2Fmanjeetkashyapsaharanpur&width=250&height=80&layout=standard&size=large&show_faces=true&appId" width="250" height="80" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>


Change facebook page name.

Monday 17 July 2017

How to hide admin bar in wordpress frontend.

If you would rather remove the toolbar with code, just drop the following snippet into your functions.php file:

add_filter('show_admin_bar', '__return_false');

What is Practice in technical language.

When I'm saying "Practice", what does it mean? I would say:

    Practice is a habit.

    Practice is a routine.

    Practice does not need to remember.

    Practice comes by practicing.

    Practice needs dedication and commitment.

Thursday 13 July 2017

How to page reload in ajax and jquery in php

How to page reload in ajax and jquery in php

<div id="manjeet"></div>

<script type='text/javascript'>

 function autoRefresh_div()
 {
      $('#manjeet').load('get_data.php');// a function which will load data from other file after x seconds
  }
  setInterval('autoRefresh_div()', 5000);

</script>

Thursday 6 July 2017

How to browser close and tab close event in JavaScript

Following javascript code you could use to detect browser close and tab close event.

window.onbeforeunload = function () {
    alert("Do you really want to close?");
};

How to check internet connection using javascript

Here is the simple javascript function for getting internet status working or not..

<script>
function checkInternetCon() {
var status = navigator.onLine;
if (status) {
alert("Yes!! Working");
} else {
alert("Sad!! Not Working ");
}
}</script>
 
 
 
 
Call above function on button onclick event.
 
 
<button onclick="checkInternetCon()">Check Internet Connection</button>
 
 
You can also use setInterval method in javascript
 
 
setInterval(function(){ 
var status = navigator.onLine;
 if (status) {
 console.log('Working..');
 } else {
  console.log('Not Working..');
 }
}, 5000); 
 
  

Wednesday 5 July 2017

How to crop image in php.

 Learn more about php GD Library http://php.net/manual/en/book.image.php
 
 create index.php file.
  
<?php
# Note: Install GD libraries 
$filename = 'image.jpg'; //orignal file 
$newFilename = 'newImage.png'; // New file after modification 
 
list($current_width, $current_height) = getimagesize($filename);
$left = 0; //crop left margin
$top = 0;//crop right margin
$cropWidth = 1056; 
$cropHeight = 400;
$canvas = imagecreatetruecolor($cropWidth, $cropHeight);
$currentImage = imagecreatefromjpeg($filename);
imagecopy($canvas, $currentImage, 0, 0, $left, $top, $currentWidth, $currentHeight);
imagejpeg($canvas, $newFilename, 100);
?>
 
 

Create pagination using corephp and phpmysql.

First of all create your Mysql database and table

CREATE TABLE IF NOT EXISTS `posts` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(200) NOT NULL,
  `description` text NOT NULL,
  `created` datetime NOT NULL,
  `updated` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;
 
 
 
 create show.php file.
 
 
<?php
$hostname = 'localhost'; // your mysql hostname
$username = 'root';   // Your mysql db username
$password = 'root';   // You mysql db password
$database = 'demo';       // mysql db name
$con = mysqli_connect($hostname, $username, $password, $database);
 
    if (isset($_GET["page"])) { 
      $page  = $_GET["page"]; 
    } else { 
      $page=1; 
    };
$recordsPerPage=20; 
$start = ($page-1) * $recordsPerPage; 
$query = "SELECT * FROM posts LIMIT $start, $recordsPerPage"; 
$result = mysqli_query($con, $query);
 
echo "<table><tr><th>Title</th><th>Description</th></tr>";
while ($row = mysqli_fetch_assoc($result)) { 
            echo "<tr>
            <td>".$row['title']."</td><td>".$row['description']."</td></tr>";            
}
echo "</table>";
 
$query = "SELECT * FROM posts"; 
$result = mysqli_query($con, $query); //run the query
$totalRecords = mysqli_num_rows($result);  //count number of records
$totalPages = ceil($totalRecords / $recordsPerPage); 
 
echo "<a href='show.php?page=1'>".'|<'."</a> "; // Go to 1st page  
 
for ($num=1; $num<=$totalPages; $num++) { 
            echo "<a href='show.php?page=".$num."'>".$num."</a> "; 
}; 
echo "<a href='show.php?page=$totalPages'>".'>|'."</a> "; // Go to last page
?> 
 

GET HTML (Parser) Using PHP

Download html parser class file from http://sourceforge.net/projects/simplehtmldom/files/

And create your project directory and create file index.php
 
 
 index.php 
 
<?php
error_reporting(0);
// call parser library
include('lib/simple_html_dom.php');
$html = file_get_html('http://webdeskers.com');
$posts = array();
foreach($html->find('tr') as $e)
{
  $data = array();
  foreach($e->find('td') as $d)
  {
   $data[] =  $d->innertext;
  }
  array_push($posts, $data);
}
 
echo "<pre>";
print_r($posts);
?>

Friday 30 June 2017

How to ADD Date Format Validation in PHP

How to ADD Date Format Validation in PHP


Using Regex

function validateDate($data) {
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]
|[1-2][0-9]|3[0-1])$/",$date))
    {
        return true;
    }else{
        return false;
    }
}
 
var_dump(validateDate("2017-02-27")) // true
var_dump(validateDate("27-02-2017")) // false
var_dump(validateDate("2017-14-27")) // false
 
 
 

Using PHP Date object

 function validateDate($date)
{
    $dt = DateTime::createFromFormat('Y-m-d', $date);
    return $dt && $dt->format('Y-m-d') === $date;
}
var_dump(validateDate("2017-02-27")) // true
var_dump(validateDate("27-02-2017")) // false
var_dump(validateDate("2017-14-27")) // false

How to display address on google map using Google Maps Embed API in php

How to display address on google map using Google Maps Embed API in php

<?php
$address = "Okhala phase 2 new delhi";
$address = str_replace(" ","+", $address);
?>
<iframe
  width="100%"
  height="400"
  frameborder="0" style="border:0"
  src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY
    &q=<?= $address ?>">
</iframe>

How to get information about your memory and CPU usage in PHP.

How to get information about your memory and CPU usage in PHP.


Thursday 29 June 2017

How to destroy / expire session after X minutes in php

function sessionTimeout($duration)
 if (isset($_SESSION['LAST_ACTIVITY']) && (time() - 
        $_SESSION['LAST_ACTIVITY'] > ($duration * 60))) {
    // last request was more than x minutes ago, where x = duration
    session_unset();     // unset $_SESSION variable for the run-time 
    session_destroy();   // destroy session data in storage
 }
}
$duration = 40; //40 minute as example
sessionTimeout($duration);
$_SESSION['LAST_ACTIVITY'] = time(); 

How to check is WEBSITE https secure or not in php

 Above single line of php code will help you to get whether current URL over https or http.
 
 
<?= ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) ? 'https' : 'http'; ?>

How to add full screen background image using CSS.




html { 
  background: url(background.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
 

MySql Interview Questions and Answers.

MySql Interview Questions and Answers

Question: What is MySQL?

MySQL is an open source relational database management system (RDBMS) that uses Structured Query Language, the most popular language for adding, accessing, and processing data in a database. Because it is open source, anyone can download MySQL and tailor it to their needs in accordance with the general public license. MySQL is noted mainly for its speed, reliability, and flexibility.

Question: What is the usage of ENUMs in MySQL?

ENUM is a string object used to specify set of predefined values and that can be used during table creation.

Question: Define REGEXP?

REGEXP is a pattern match in which matches pattern anywhere in the search value.
See REGEXP eg: How to search for exact matched word using MySql Query

Question: How do you get the number of rows in MYSql?

SELECT COUNT (id) FROM items



Question: How do you return the a hundred items starting from 20th position?

SELECT item_name FROM items LIMIT 20, 100.
Where the first number in LIMIT is the offset, the second is the number.

Question: Give string types available for column in MYSql?

Following are the string types in MYSql
* SET
* BLOB
* ENUM
* CHAR
* TEXT
* VARCHAR

Question: What are the disadvantages of MySQL?

* MySQL is not so efficient for large scale databases.
* It does not support COMMIT and STORED PROCEDURES functions version less than 5.0.
* Transactions are not handled very efficiently.

Question: How many columns can you create for an index?

You can create maximum of 16 indexed columns for a standard table.

Question: How to get current MySQL version?

SELECT VERSION ();

Question: What is the difference between primary key and candidate key?

Every row of a table is identified uniquely by primary key. There is only one primary key for a table.
Primary Key is also a candidate key. By common convention, candidate key can be designated as primary and which can be used for any foreign key references.

Question: What is the query to display current date and time?

SELECT NOW();
-- Display only current date
SELECT CURRENT_DATE();

Question: What is InnoDB?

lnnoDB is a transaction safe storage engine developed by Innobase Oy which is a Oracle Corporation now.

Question: How can we run batch mode in mysql?

mysql ;
mysql mysql.out

Question: What is MySQL data directory?

MySQL data directory is a place where MySQL stores its data. Each subdirectory under this data dictionary represents a MySQL database. By default the information managed my MySQL = server mysqld is stored in data directory.

Question: What is the use of mysql_close()?

it can be used to close connection opened by mysql_connect() function.

Question: Why MySQL is used?

MySQL database server is reliable, fast and very easy to use. This software can be downloaded as freeware and can be downloaded from the internet

Question: In which language MySQL is written?

MySQL is written in C and C++ and its SQL parser is written in yacc.



Question: What are the technical features of MySQL?

MySQL has the following technical features:-
* Flexible structure
* High performance
* Manageable and easy to use
* Replication and high availability
* Security and storage management

Question: What is maximum length of column name, table name and database name?

column name can be upto 64 chars, table name can be upto 64 and database name can be upto 64 chars.

Monday 12 June 2017

How to fetch youtube video data in API using php.

https://www.youtube.com/watch?v=ABHFLHVQ123
In this URL your youtube video id is showing in red color.


<?php $data = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=YOUTUBE_VIDEO_ID&key=YOUR_YOUTUBE_APIKEY&part=snippet,contentDetails,statistics,status");  

$result = json_decode($data, true); 
 echo "<pre>"; print_r($result); 

 ?>

You can learn more about youtube data api from https://developers.google.com/youtube/v3/getting-started