PHP中如何解决include场景下&被转义为&的问题?
PHP include场景下&被替换为&的问题解决
问题描述
在include场景中,生成请求URL时出现&被自动替换为&的情况,导致URL格式错误,无法正常发起请求。
相关代码
$merchantRefNumber = $payment[ID]; $signature = $merchantCode.$merchantRefNumber.$secureKey; $signature = hash('sha256', $signature); $URL = ("https://www.atfawry.com/ECommerceWeb/Fawry/payments/status?merchantCode=".($merchantCode)."&merchantRefNumber=".($merchantRefNumber)."&signature=".($signature)); $response = file_get_contents($URL); if ( $response ) { // 后续逻辑 }
错误生成的URL
https://www.atfawry.com/ECommerceWeb/Fawry/payments/status?merchantCode=CB8Q95Jr&merchantRefNumber=AGHUY&signature=135bfd157a9ac13931b512120609dc31ff31879
正确的URL格式
https://www.atfawry.com/ECommerceWeb/Fawry/payments/status?merchantCode=CB8Q95Jr&merchantRefNumber=AGHUY&signature=135bfd157a9ac13931b512120609dc31ff31879
解决方法
1. 排查并移除不必要的HTML转义
这类问题通常是代码中(包括被include的文件)存在htmlspecialchars、htmlentities这类HTML转义函数,对URL变量做了不必要的转义。检查所有涉及该URL变量的代码,移除这类多余的转义操作。
2. 使用http_build_query规范构建URL
手动拼接URL参数容易出现转义或格式错误,推荐用PHP内置的http_build_query函数构建查询参数,它会自动处理参数分隔符和编码,从根源避免这类问题:
$merchantRefNumber = $payment['ID']; // 建议给数组键名加引号,避免未定义常量警告 $signature = $merchantCode . $merchantRefNumber . $secureKey; $signature = hash('sha256', $signature); // 构造参数数组 $queryParams = [ 'merchantCode' => $merchantCode, 'merchantRefNumber' => $merchantRefNumber, 'signature' => $signature ]; // 拼接完整URL $URL = 'https://www.atfawry.com/ECommerceWeb/Fawry/payments/status?' . http_build_query($queryParams); $response = file_get_contents($URL); if ($response) { // 后续逻辑 }
3. 临时修复:还原已转义的URL(不推荐作为长期方案)
如果暂时无法找到转义的根源,可以用htmlspecialchars_decode函数将已转义的URL还原:
$URL = htmlspecialchars_decode($URL); $response = file_get_contents($URL);
但这只是临时修复,建议优先从根源解决问题。
内容的提问来源于stack exchange,提问作者Sea Memories
相关产品推荐
相关产品推荐

