You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP无法读取Base64编码的HTTP POST请求及解码乱码问题

问题原因及解决办法

核心问题分析

  1. 使用text/plain;base64作为Content-Type时:
    PHP的$_REQUEST、$_POST只会自动解析application/x-www-form-urlencoded或multipart/form-data这两种标准POST请求格式,所以直接用var_dump($_REQUEST)看不到数据——因为PHP不会自动解析非标准的请求体。

  2. 使用application/x-www-form-urlencoded时解码乱码:
    Base64编码后的字符串包含+、/、=这类字符,而在application/x-www-form-urlencoded格式中,+会被自动解析成空格,/和=也会被转义,导致Base64解码后出现大量异常字符。


针对性解决方案

方案1:改用text/plain发送,接收端读取原始请求体

Python发送端代码调整:

import requests
import base64

# 示例HTML内容,实际可从文件或网页抓取获取
html_content = "<html><body><h1>测试网页内容</h1></body></html>"
# 将HTML转字节后Base64编码,再转回字符串
base64_data = base64.b64encode(html_content.encode("utf-8")).decode("utf-8")

# 发送请求,Content-Type设为text/plain即可,PHP不识别;base64后缀
headers = {"Content-Type": "text/plain"}
response = requests.post("http://你的PHP接口地址", data=base64_data, headers=headers)

print(response.text)

PHP接收端代码调整:

<?php
// 读取原始POST请求体(不受Content-Type限制)
$raw_post_data = file_get_contents("php://input");
// 对原始数据做Base64解码
$decoded_html = base64_decode($raw_post_data);

echo "解码后的HTML内容:<br>";
// 用htmlspecialchars避免HTML标签被浏览器直接解析
echo htmlspecialchars($decoded_html);
?>

方案2:继续用application/x-www-form-urlencoded,对Base64字符串做URL编码

Python发送端代码调整:

import requests
import base64
import urllib.parse

html_content = "<html><body><h1>测试网页内容</h1></body></html>"
base64_data = base64.b64encode(html_content.encode("utf-8")).decode("utf-8")
# 对Base64字符串做URL编码,避免特殊字符被转义
url_safe_base64 = urllib.parse.quote(base64_data)

# 以键值对形式发送,参数名可自定义(比如html_data)
response = requests.post("http://你的PHP接口地址", data={"html_data": url_safe_base64})

print(response.text)

PHP接收端代码调整:

<?php
if (isset($_POST["html_data"])) {
    # 先对收到的参数做URL解码,再Base64解码
    $base64_str = urldecode($_POST["html_data"]);
    $decoded_html = base64_decode($base64_str);

    echo "解码后的HTML内容:<br>";
    echo htmlspecialchars($decoded_html);
} else {
    echo "未收到有效参数";
}
?>

内容的提问来源于stack exchange,提问作者david

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 06:29:55