Super useful 7 PHP code snippets to share

  • 2020-05-10 17:50:35
  • OfStack

1. Super simple page caching
If your project is not based on an CMS system or framework, building a simple caching system will be very practical. The code below is simple, but it's a real fix for a small site.
 
<?php 
// define the path and name of cached file 
$cachefile = 'cached-files/'.date('M-d-Y').'.php'; 
// define how long we want to keep the file in seconds. I set mine to 5 hours. 
$cachetime = 18000; 
// Check if the cached file is still fresh. If it is, serve it up and exit. 
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) { 
include($cachefile); 
exit; 
} 
// if there is either no file OR the file to too old, render the page and capture the HTML. 
ob_start(); 
?> 
<html> 
output all your html here. 
</html> 
<?php 
// We're done! Save the cached content to a file 
$fp = fopen($cachefile, 'w'); 
fwrite($fp, ob_get_contents()); 
fclose($fp); 
// finally send browser output 
ob_end_flush(); 
?> 

Click here to view the details: http: / / wesbos com/simple - php - page - caching - technique /

2. Calculate the distance in PHP
This is a very useful distance calculation function that USES latitude and longitude to calculate the distance from the A site to the B site. This function can return miles, kilometers, nautical miles of three unit types of distance.
 
function distance($lat1, $lon1, $lat2, $lon2, $unit) { 

$theta = $lon1 - $lon2; 
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
$dist = acos($dist); 
$dist = rad2deg($dist); 
$miles = $dist * 60 * 1.1515; 
$unit = strtoupper($unit); 

if ($unit == "K") { 
return ($miles * 1.609344); 
} else if ($unit == "N") { 
return ($miles * 0.8684); 
} else { 
return $miles; 
} 
} 

Usage:
 
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k")." kilometers"; 

Click here to view the details: http: / / www phpsnippets. info/calculate - distances in -- php

3. Convert the number of seconds into time (year, month, day, hour...)
This useful function converts the number of seconds represented by an event into a time format of year, month, day, hour, and so on.
 
function Sec2Time($time){ 
if(is_numeric($time)){ 
$value = array( 
"years" => 0, "days" => 0, "hours" => 0, 
"minutes" => 0, "seconds" => 0, 
); 
if($time >= 31556926){ 
$value["years"] = floor($time/31556926); 
$time = ($time%31556926); 
} 
if($time >= 86400){ 
$value["days"] = floor($time/86400); 
$time = ($time%86400); 
} 
if($time >= 3600){ 
$value["hours"] = floor($time/3600); 
$time = ($time%3600); 
} 
if($time >= 60){ 
$value["minutes"] = floor($time/60); 
$time = ($time%60); 
} 
$value["seconds"] = floor($time); 
return (array) $value; 
}else{ 
return (bool) FALSE; 
} 
} 

Click here to view the details: http: / / ckorp net/sec2time php

4. Download files compulsively
Some files, such as mp3, are usually played or used directly in the client browser. If you want them to be downloaded compulsively, that's fine. You can use the following code:
 
function downloadFile($file){ 
$file_name = $file; 
$mime = 'application/force-download'; 
header('Pragma: public'); // required 
header('Expires: 0'); // no cache 
header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
header('Cache-Control: private',false); 
header('Content-Type: '.$mime); 
header('Content-Disposition: attachment; filename="'.basename($file_name).'"'); 
header('Content-Transfer-Encoding: binary'); 
header('Connection: close'); 
readfile($file_name); // push it out 
exit(); 
} 

Click here for details: Credit: Alessio Delmonti

5. Get current weather information using Google API
Want to know the weather today? This code will tell you that it only takes three lines of code. You just need to replace the ADDRESS with the city you want.
 
$xml = simplexml_load_file('http://www.google.com/ig/api?weather=ADDRESS'); 
$information = $xml->xpath("/xml_api_reply/weather/current_conditions/condition"); 
echo $information[0]->attributes(); 

Click here to view the details: http: / / ortanotes tumblr. com/post / 200469319 / current - weather - in - 3 - lines - of - php

Get the latitude and longitude of an address
With the popularity of Google Maps API, developers often need to obtain the latitude and longitude of a particular location. This useful function takes an address and returns an array of latitude and longitude data.
 
function getLatLong($address){ 
if (!is_string($address))die("All Addresses must be passed as a string"); 
$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address)); 
$_result = false; 
if($_result = file_get_contents($_url)) { 
if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false; 
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match); 
$_coords['lat'] = $_match[1]; 
$_coords['long'] = $_match[2]; 
} 
return $_coords; 
} 

Click here to view the details: http: / / snipplr com/view php? codeview & id = 47806

7. Get the favicon icon of the domain name using PHP and Google
Some websites or Web applications require favicon ICONS from other websites. This is easy to do with Google and PHP, but only if the Google connection is not reset!
 
function get_favicon($url){ 
$url = str_replace("http://",'',$url); 
return "http://www.google.com/s2/favicons?domain=".$url; 
} 

Click here to view the details: http: / / snipplr com/view php? codeview & id = 45928

Related articles: