PHP file_get_contents异常:直接调用正常,JS传参返回空
问题解决:PHP脚本通过JS传参调用返回空结果
问题描述
grabber.php脚本硬编码URL时能正常返回内容,但通过JavaScript传参调用时返回空结果:
PHP代码(grabber.php)
<?php $url = $_GET['url']; //$url = 'https://www.google.com/search?q=usd+to+egp/'; echo file_get_contents($url);
JavaScript代码
const usdPriceURI = 'https://www.google.com/search?q=usd+to+egp/' $('#responseUsd').load('/php/grabber.php?url=' + usdPriceURI);
原因分析
JS直接拼接URL时,目标URL里的?、=、+等特殊字符会破坏HTTP请求的参数结构,导致PHP接收到的$_GET['url']是不完整的错误地址(比如仅拿到https://www.google.com/search),自然无法获取有效内容。
另外,Google可能识别出非浏览器发起的请求,直接返回空内容或反爬页面,这也是硬编码能成功(本地测试时可能模拟了浏览器请求头)但JS调用失败的潜在原因。
解决方案
1. 对JS中的URL参数编码
使用encodeURIComponent()转义特殊字符,确保参数完整传递:
const usdPriceURI = 'https://www.google.com/search?q=usd+to+egp/' $('#responseUsd').load('/php/grabber.php?url=' + encodeURIComponent(usdPriceURI));
2. PHP模拟浏览器请求头
为避免被反爬,给file_get_contents添加浏览器请求头:
<?php $url = $_GET['url']; $opts = [ 'http' => [ 'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n" ] ]; $context = stream_context_create($opts); echo file_get_contents($url, false, $context);
3. 检查PHP配置
确保php.ini中allow_url_fopen设置为On,否则file_get_contents无法获取远程URL内容。
内容的提问来源于stack exchange,提问作者Ahmed Nazmy
相关产品推荐
相关产品推荐

