首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

7 個超實用 PHP 代碼片段:頁面緩存、距離計算、時間格式化等

     編輯:PHP 相關知識

不依賴框架的輕量級項目,幾個精心封裝的工具函數能解決 80% 通用需求。本文精選 7 個高復用代碼片段,開箱即用。

1. 輕量級頁面緩存 (5 小時過期)

<?php
$cacheFile = 'cache/' . date('Y-m-d') . '.html';
$cacheTime = 18000; // 5 hours

if (file_exists($cacheFile) && (time() - $cacheTime < filemtime($cacheFile))) {
    include $cacheFile;
    exit;
}

ob_start();
?>
<html><body>
    
</body></html>
<?php
$fp = fopen($cacheFile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
?>

原理:首次請求輸出緩存到文件,後續請求直接 include 靜態 HTML,繞過 PHP 解析。

2. 經緯度距離計算 (支持公里/英里/海裡)

function distance($lat1, $lon1, $lat2, $lon2, $unit = 'K') {
    $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;      // 公里
    if ($unit == 'N') return $miles * 0.8684;        // 海裡
    return $miles;                                   // 英里
}

// 用法
echo distance(32.9697, -96.80322, 29.46786, -98.53506, 'k') . " kilometers";

3. 秒數轉人類可讀時間 (年/月/日/時/分/秒)

function sec2time($seconds) {
    if (!is_numeric($seconds)) return false;
    $units = [
        'years'   => 31556926,
        'days'    => 86400,
        'hours'   => 3600,
        'minutes' => 60,
        'seconds' => 1,
    ];
    $result = [];
    foreach ($units as $name => $unitSecs) {
        if ($seconds >= $unitSecs) {
            $result[$name] = floor($seconds / $unitSecs);
            $seconds %= $unitSecs;
        } else {
            $result[$name] = 0;
        }
    }
    return $result;
}

// 返回 ['years'=>0, 'days'=>2, 'hours'=>5, 'minutes'=>30, 'seconds'=>15]

4. 關鍵詞高亮 (搜索結果標紅)

function highlight($text, array $keywords) {
    if (empty($keywords) || !is_string($text)) return $text;
    $pattern = '/\b(' . implode('|', array_map('preg_quote', $keywords)) . ')\b/i';
    return preg_replace($pattern, '<mark>$1</mark>', $text);
}

5. Feedburner 訂閱數獲取 (7 天平均)

function get_feedburner_avg($feedId, $days = 7) {
    $today = date('Y-m-d');
    $ago   = date('Y-m-d', strtotime("-$days days"));
    $url   = "https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=$feedId&dates=$ago,$today";
    $xml   = simplexml_load_string(file_get_contents($url));
    $total = 0;
    foreach ($xml->feed->entry as $entry) {
        $total += (int)$entry['circulation'];
    }
    return round($total / $days);
}

6. 安全隨機密碼生成器 (可控強度)

function generatePassword($length = 12, $strength = 4) {
    $vowels = 'aeuy';
    $cons   = 'bdghjmnpqrstvz';
    if ($strength >= 1) $cons .= 'BDGHJLMNPQRSTVWXZ';
    if ($strength >= 2) $vowels .= 'AEUY';
    if ($strength >= 4) $cons .= '23456789';
    if ($strength >= 8) $vowels .= '@#$%';

    $pool = $vowels . $cons;
    $pwd  = '';
    for ($i = 0; $i < $length; $i++) {
        $pwd .= $pool[random_int(0, strlen($pool) - 1)];
    }
    return $pwd;
}

7. 多 CSS 文件合併壓縮輸出

header('Content-Type: text/css');
ob_start('compress_css');

function compress_css($buffer) {
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); // 註釋
    $buffer = str_replace(["\r\n", "\r", "\n", "\t", '  ', '    '], '', $buffer); // 空白
    return $buffer;
}

include 'css/reset.css';
include 'css/layout.css';
include 'css/theme.css';

ob_end_flush();

使用建議

  • 將上述函數集中放入 helpers.php,入口文件 require_once 載入。
  • 生產環境關閉 display_errors,錯誤寫日誌,避免輸出污染緩存/壓縮輸出。
  • 涉及用戶輸入的片段 (搜索高亮、密碼生成) 嚴格驗證輸入長度與字符集。

這 7 個片段覆蓋緩存、地理、時間、搜索、數據源、安全、前端優化 7 大高頻場景,是中小型 PHP 專案的「瑞士軍刀」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved