欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

7个超级实用的PHP代码片段分享(1)

程序员文章站 2022-05-08 19:08:02
...
1、超级简单的页面缓存

如果你的工程项目不是基于 CMS 系统或框架,打造一个简单的缓存系统将会非常实在。下面的代码很简单,但是对小网站而言能切切实实解决问题。

  1. // define the path and name of cached file
  2. $cachefile = 'cached-files/'.date('M-d-Y').'.php';
  3. // define how long we want to keep the file in seconds. I set mine to 5 hours.
  4. $cachetime = 18000;
  5. // Check if the cached file is still fresh. If it is, serve it up and exit.
  6. if (file_exists($cachefile) && time() - $cachetime filemtime($cachefile)) {
  7. include($cachefile);
  8. exit;
  9. }
  10. // if there is either no file OR the file to too old, render the page and capture the HTML.
  11. ob_start();
  12. ?>
  13. output all your html here.
  14. // We're done! Save the cached content to a file
  15. $fp = fopen($cachefile, 'w');
  16. fwrite($fp, ob_get_contents());
  17. fclose($fp);
  18. // finally send browser output
  19. ob_end_flush();
  20. ?>

点击这里查看详细情况:http://wesbos.com/simple-php-page-caching-technique/

2、在 PHP 中计算距离

这是一个非常有用的距离计算函数,利用纬度和经度计算从 A 地点到 B 地点的距离。该函数可以返回英里,公里,海里三种单位类型的距离。

  1. function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  2. $theta = $lon1 - $lon2;
  3. $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  4. $dist = acos($dist);
  5. $dist = rad2deg($dist);
  6. $miles = $dist * 60 * 1.1515;
  7. $unit = strtoupper($unit);
  8. if ($unit == "K") {
  9. return ($miles * 1.609344);
  10. } else if ($unit == "N") {
  11. return ($miles * 0.8684);
  12. } else {
  13. return $miles;
  14. }
  15. }

使用方法:

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

点击这里查看详细情况:http://www.phpsnippets.info/calculate-distances-in-php

3、将秒数转换为时间(年、月、日、小时…)

这个有用的函数能将秒数表示的事件转换为年、月、日、小时等时间格式。

  1. function Sec2Time($time){
  2. if(is_numeric($time)){
  3. $value = array(
  4. "years" => 0, "days" => 0, "hours" => 0,
  5. "minutes" => 0, "seconds" => 0,
  6. );
  7. if($time >= 31556926){
  8. $value["years"] = floor($time/31556926);
  9. $time = ($time%31556926);
  10. }
  11. if($time >= 86400){
  12. $value["days"] = floor($time/86400);
  13. $time = ($time%86400);
  14. }
  15. if($time >= 3600){
  16. $value["hours"] = floor($time/3600);
  17. $time = ($time%3600);
  18. }
  19. if($time >= 60){
  20. $value["minutes"] = floor($time/60);
  21. $time = ($time%60);
  22. }
  23. $value["seconds"] = floor($time);
  24. return (array) $value;
  25. }else{
  26. return (bool) FALSE;
  27. }
  28. }

点击这里查看详细情况:http://ckorp.net/sec2time.php

1