Super Practical 7 pieces of PHP code to share _php tips

Source: Internet
Author: User
Tags cos sin
1, Super simple page Caching
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 the problem for small web sites.
Copy Code code as follows:

<?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 ();
?>
Output all your HTML here.
<?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 details: http://wesbos.com/simple-php-page-caching-technique/

2. Calculate the distance in PHP
This is a very useful distance calculation function, using latitude and longitude to calculate the distance from A location to B location. The function can return miles, kilometers, nautical kilometres of three units of distance.
Copy Code code 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 Code code as follows:

echo Distance (32.9697, -96.80322, 29.46786, -98.53506, "K"). "Kilometers";

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

3, convert the number of seconds to the time (year, month, day, hour ...). )
This useful function converts the event in seconds to a time format such as year, month, day, hour, and so on.
Copy Code code as follows:

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 details: http://ckorp.net/sec2time.php

4. Force download file
Some files, such as the MP3 type, are usually played or used directly in the client browser. If you want them to be forced to be downloaded, there's no problem. You can use the following code:
Copy Code code 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 view details: Credit:alessio delmonti

5, use the Google API to get the current weather information
Want to know the weather today? This code will tell you just 3 lines of code. You just need to change the address to the city you want.
Copy Code code 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 view 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 Google's Maps API, developers often need to get latitude and longitude at a particular location. This very useful function takes an address as an argument and returns an array that contains the longitude and latitude data.
Copy Code code as follows:

function Getlatlong ($address) {
if (!is_string ($address)) Die ("All Addresses must to 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 details: http://snipplr.com/view.php?codeview&id=47806

7, use PHP and Google to obtain domain name Favicon icon
Some Web sites or Web applications need to use the Favicon icon from other sites. Google and PHP can be easily done, but only if Google is not connected to the reset Oh!
Copy Code code as follows:

function Get_favicon ($url) {
$url = Str_replace ("http://", "", $url);
Return "http://www.google.com/s2/favicons?domain=". $url;
}

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

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.