萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 實用代碼片段庫:重定向、UA 解析、文件操作、頁面跳轉

1. 三種頁面重定向方式

<?php
// 方法一:HTTP Header(推薦,必須在輸出前)
header("Location: index.php");
exit;

// 方法二:JavaScript(需瀏覽器支援 JS)
echo '<script>window.location = "' . $_SERVER['PHP_SELF'] . '";</script>';

// 方法三:HTML Meta 標籤(延遲跳轉)
echo '<meta http-equiv="Refresh" content="0; URL=index.php">';
?>

2. 獲取訪客瀏覽器信息

<?php
function getBrowserInfo() {
    $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $browsers = [
        '/msie/i' => 'Internet Explorer',
        '/firefox/i' => 'Firefox',
        '/chrome/i' => 'Chrome',
        '/safari/i' => 'Safari',
        '/opera/i' => 'Opera',
        '/edge/i' => 'Edge',
    ];
    foreach ($browsers as $pattern => $name) {
        if (preg_match($pattern, $agent)) {
            // 簡易版本號提取
            preg_match($pattern . '[\s/]([\d.]+)', $agent, $matches);
            $version = $matches[1] ?? '';
            return "$name $version";
        }
    }
    return 'Unknown';
}
echo getBrowserInfo();
?>

3. 獲取訪客操作系統

<?php
function getOSInfo() {
    $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $osList = [
        '/windows nt 10.0/i' => 'Windows 10',
        '/windows nt 6.3/i' => 'Windows 8.1',
        '/windows nt 6.2/i' => 'Windows 8',
        '/windows nt 6.1/i' => 'Windows 7',
        '/windows nt 6.0/i' => 'Windows Vista',
        '/windows nt 5.1/i' => 'Windows XP',
        '/macintosh|mac os x/i' => 'macOS',
        '/linux/i' => 'Linux',
        '/android/i' => 'Android',
        '/iphone|ipad/i' => 'iOS',
    ];
    foreach ($osList as $pattern => $name) {
        if (preg_match($pattern, $agent)) return $name;
    }
    return 'Unknown';
}
echo getOSInfo();
?>

4. 常見 MIME 類型映射表

<?php
$mimeTypes = [
    // 圖片
    'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg',
    'png' => 'image/png', 'bmp' => 'image/bmp', 'webp' => 'image/webp',
    'svg' => 'image/svg+xml', 'ico' => 'image/x-icon',
    // 文檔
    'pdf' => 'application/pdf', 'doc' => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'xls' => 'application/vnd.ms-excel',
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'ppt' => 'application/vnd.ms-powerpoint',
    'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'txt' => 'text/plain', 'csv' => 'text/csv',
    // 壓縮
    'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed',
    'gz' => 'application/gzip', 'tar' => 'application/x-tar',
    '7z' => 'application/x-7z-compressed',
    // 音視頻
    'mp3' => 'audio/mpeg', 'wav' => 'audio/wav', 'mp4' => 'video/mp4',
    'webm' => 'video/webm', 'flv' => 'video/x-flv',
    // 代碼
    'js' => 'application/javascript', 'json' => 'application/json',
    'xml' => 'application/xml', 'css' => 'text/css',
    'html' => 'text/html', 'php' => 'application/x-httpd-php',
];
// 使用:$mime = $mimeTypes[pathinfo($file, PATHINFO_EXTENSION)] ?? 'application/octet-stream';
?>

5. 文件讀寫封裝函數

<?php
function readFileSafe(string $file): ?string {
    if (!is_file($file)) return null;
    $fp = fopen($file, 'rb');
    flock($fp, LOCK_SH);
    $content = fread($fp, filesize($file));
    flock($fp, LOCK_UN);
    fclose($fp);
    return $content;
}

function writeFileSafe(string $file, string $data, string $mode = 'wb'): int|false {
    $fp = fopen($file, $mode);
    flock($fp, LOCK_EX);
    $bytes = fwrite($fp, $data);
    flock($fp, LOCK_UN);
    fclose($fp);
    return $bytes;
}
?>

6. 友好頁面跳轉提示

<?php
function redirectWithMsg(string $url = 'index.php', string $msg = '頁面跳轉中...', int $sec = 2): never {
    header("Content-Type: text/html; charset=utf-8");
    echo "<!DOCTYPE html><html><head><meta charset='utf-8'>";
    echo "<meta http-equiv='refresh' content='$sec;url=$url'>";
    echo "<title>$msg</title><style>body{font:14px/1.5 sans-serif;text-align:center;padding-top:10vh}</style>";
    echo "</head><body>$msg<br><a href='$url'>點此手動跳轉</a></body></html>";
    exit;
}
// 用法:redirectWithMsg('list.php', '刪除成功,2秒後返回列表');
?>
copyright © 萬盛學電腦網 all rights reserved