7 super-useful PHP snippet _php Tutorials

Source: Internet
Author: User
1. Super Simple page Cache
If your project is not based on a CMS system or framework, creating a simple caching system will be very real. The following code is simple, but it can solve a problem for small sites.
Copy CodeThe code is as follows:
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 ();
?>

Output all your the HTML here.

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 see details: http://wesbos.com/simple-php-page-caching-technique/

2. Calculate the distance in PHP
This is a very useful distance calculation function that calculates the distance from location A to location B using latitude and longitude. The function can return miles, kilometers, and oceans of three unit types of distance.
Copy CodeThe code is as follows:
function distance ($lat 1, $lon 1, $lat 2, $lon 2, $unit) {
$theta = $lon 1-$lon 2;
$dist = sin (Deg2rad ($lat 1)) * Sin (Deg2rad ($lat 2)) + cos (Deg2rad ($lat 1)) * cos (Deg2rad ($lat 2)) * 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;
}
}

How to use:
Copy CodeThe code is as follows:
echo Distance (32.9697, -96.80322, 29.46786, -98.53506, "K"). "Kilometers";

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

3. Convert the number of seconds to time (year, month, day, hour ...) )
This useful function converts the events represented by the number of seconds to the time format of year, month, day, and hour.
Copy CodeThe code is as follows:
function Sec2time ($time) {
if (Is_numeric ($time)) {
$value = Array (
"Years" = 0, "days" = 0, "hours" = 0,
"Minutes" = 0, "Seconds" and "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 see details: http://ckorp.net/sec2time.php

4. Force download file
Some files, such as the MP3 type, are typically played or used directly in the client browser. If you want them to be forced to be downloaded, no problem. You can use the following code:
Copy CodeThe code is as follows:
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 to see 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 3 lines of code. You just need to change the ADDRESS to the city you want.
Copy CodeThe code is as follows:
$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 see details: http://ortanotes.tumblr.com/post/200469319/current-weather-in-3-lines-of-php

6, to obtain the latitude and longitude of an address
With the popularity of the Google Maps API, developers often need to get latitude and longitude for a particular location. This very useful function takes an address as an argument and returns an array containing the longitude and latitude data.
Copy CodeThe code is as follows:
function Getlatlong ($address) {
if (!is_string ($address)) Die ("All Addresses must is 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 see details: http://snipplr.com/view.php?codeview&id=47806

7. Favicon icons for domain names using PHP and Google
Some Web sites or Web applications require the use of favicon icons from other websites. Google and PHP are easy to handle, but only if Google doesn't connect to reset it!
Copy CodeThe code is as follows:
function Get_favicon ($url) {
$url = Str_replace ("http://", "', $url);
Return "http://www.google.com/s2/favicons?domain=". $url;
}

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

http://www.bkjia.com/PHPjc/323856.html www.bkjia.com true http://www.bkjia.com/PHPjc/323856.html techarticle 1, Super simple page cache if your project is not based on a CMS system or framework, creating a simple caching system will be very real. The following code is simple, but to small ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.