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

PHP 開發實戰技巧集錦:重定向、UA 解析、Mime 類型、Excel 導出、時間比較、DB 封裝

     編輯:PHP 綜合知識

項目告一段落,整理六大高頻實用技巧,代碼可直接落地。

1. 三種重定向方式

// ① HTTP Header(推薦,無輸出前調用)
header("Location: index.php");

// ② JavaScript
echo "<script>window.location = '$PHP_SELF';</script>";

// ③ Meta Refresh
echo '<meta http-equiv="Refresh" content="0; URL=index.php">';

2. 瀏覽器/UA 解析函數

function browse_infor() {
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $browsers = ['Lynx','MOSAIC','AOL','Opera','JAVA','MacWeb','WebExplorer','OmniWeb'];
    foreach ($browsers as $b) {
        if (strpos($agent, $b)) return $b;
    }
    // 主流瀏覽器深度解析(Netscape/IE/Opera)
    if (preg_match('/Mozilla.*MSIE/i', $agent)) return 'Internet Explorer ' . _extract_version($agent, 'MSIE');
    if (preg_match('/Mozilla.*Opera/i', $agent)) return 'Opera ' . _extract_version($agent, 'Opera');
    if (preg_match('/Mozilla(?!.*MSIE)(?!.*Opera)/i', $agent)) return 'Netscape Navigator ' . _extract_version($agent, 'Mozilla');
    return 'Unknown';
}

function _extract_version($agent, $pattern) {
    // 簡化版版本提取邏輯
    return 'x.x';
}

3. 作業系統識別

function osinfo() {
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $os_map = [
        'Windows 95' => '/win.*95/i',
        'Windows ME' => '/win 9x.*4\.90/i',
        'Windows 98' => '/win.*98/i',
        'Windows 2000' => '/win.*nt 5\.0/i',
        'Windows NT' => '/win.*nt/i',
        'Windows XP' => '/win.*nt 5\.1/i',
        'Linux' => '/linux/i',
        'Unix' => '/unix/i',
        'Macintosh' => '/mac.*pc/i',
        'FreeBSD' => '/freebsd/i',
        // ... 更多
    ];
    foreach ($os_map as $name => $regex) {
        if (preg_match($regex, $agent)) return $name;
    }
    return 'Unknown';
}

4. 完整 MIME 類型映射表

$mime_types = [
    'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'png' => 'image/png',
    'pdf' => 'application/pdf', 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed',
    'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4',
    'doc' => 'application/msword', 'xls' => 'application/vnd.ms-excel',
    // ... 含圖片、文檔、音視頻、壓縮包、代碼等 100+ 擴展名
];

5. PHP 直接輸出 Excel (無需第三方庫)

header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: filename=export.xls");
echo "欄位1\t欄位2\t欄位3\n";
echo "數據1\t數據2\t數據3\n";
// \t 分隔列,\n 換行,瀏覽器直接彈出下載

同理修改 Header 可輸出 .doc .csv 等格式。

6. 時間比較:標記「今日新帖」

// 方法一:24小時內
$today = time();
$yesterday = date('Y-m-d H:i:s', $today - 86400);
$is_new = $row['post_time'] >= $yesterday;

// 方法二:當天 00:00:00 起(更符合直覺)
$is_new = $row['post_time'] >= date('Y-m-d 00:00:00');

7. 數據庫操作封裝

附件提供完整封裝類(連接、查詢、事務、預處理、錯誤處理),核心思想:

  • 單例模式管理連接
  • 統一異常拋出
  • 支援預處理語句防注入
  • 調試模式輸出 SQL 執行時間

細節決定成敗,這些「小工具」組合起來就是高效開發的基建設施。

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