不依賴框架的輕量級項目,幾個精心封裝的工具函數能解決 80% 通用需求。本文精選 7 個高復用代碼片段,開箱即用。
<?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 解析。
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";
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]
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);
}
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);
}
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;
}
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 專案的「瑞士軍刀」。