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();