Super practical 7 PHP code snippets sharing _ PHP Tutorial

Source: Internet
Author: User
Super practical seven PHP code snippets to share. 1. super simple page cache if your project is not based on the CMS system or framework, it will be very practical to build a simple cache system. The following code is very simple, 1. super simple page cache
If your project is not based on a CMS system or framework, creating a simple cache system will be very practical. The following code is very simple, but it can solve problems for small websites.

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

2. calculate distance in PHP
This is A very useful distance calculation function. it uses latitude and longitude to calculate the distance from location A to location B. This function returns the distance of three units in miles, kilometers, and nautical miles.

The code is as follows:


Function distance ($ lat1, $ lon1, $ lat2, $ lon2, $ unit ){

$ Theta = $ lon1-$ lon2;
$ Dist = sin (deg 2rad ($ lat1) * sin (deg 2rad ($ lat2) + cos (deg 2rad ($ lat1 )) * cos (deg 2rad ($ lat2) * cos (deg 2rad ($ 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:

The code is 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 an event in seconds to a time format such as year, month, day, and hour.

The code is 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 File Download
Some mp3 files are usually played or used directly in the client browser. It's okay if you want them to be forcibly downloaded. You can use the following code:

The 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 view details: Credit: Alessio Delmonti

5. Use Google API to obtain current weather information
Want to know the weather today? This code will tell you that only three lines of code are required. You only need to replace the ADDRESS with the desired city.

The 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 view details: http://ortanotes.tumblr.com/post/200469319/current-weather-in-3-lines-of-php

6. obtain the longitude and latitude of an address
With the popularity of Google Maps APIs, developers often need to obtain the longitude and latitude of a specific location. This very useful function uses an address as a parameter and returns an array containing longitude and latitude data.

The code is as follows:


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, 'errortids')> 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 get the favicon of the domain name
Some websites or Web applications need to use the favicon from other websites. Google and PHP can be easily used, but the premise is that Google will not be reset!

The 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 view details: http://snipplr.com/view.php? Codeview/id = 45928

If your project is not based on a CMS system or framework, creating a simple cache system will be very practical. The following code is very simple, but for small...

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.