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

PHP base64 編碼解碼亂碼真兇:GET 傳輸中 + 號被轉空格

     編輯:PHP 綜合知識

問題重現

// 編碼跳轉
header('Location: redirect.php?message=' . base64_encode('修改成功'));

// 解碼顯示
echo base64_decode($_GET['message']); // 亂碼

根本原因

Base64 編碼字元集包含 + / =。URL 傳輸時 + 被解析為空格,導致解碼失敗。

一行修復

$str = base64_decode(str_replace(' ', '+', $_GET['str']));

完整範例

// 導向端
function _alert(bool $success, string $msg, int $time = 3, string $url = '/') {
    header('Location: /include/redirect.php?success=' . (int)$success
        . '&message=' . base64_encode($msg)
        . '&time=' . $time
        . '&url=' . base64_encode($url));
    exit;
}

// 接收端 redirect.php
$message = base64_decode(str_replace(' ', '+', $_GET['message']));
$url = base64_decode(str_replace(' ', '+', $_GET['url']));

進階:URL 安全 Base64

參考 RFC 4648 §5 標準,將 +/= 替換為 -_ 並移除填充:

function urlsafe_b64encode(string $data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function urlsafe_b64decode(string $data): string {
    $data = strtr($data, '-_', '+/');
    return base64_decode($data . str_repeat('=', (4 - strlen($data) % 4) % 4));
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved