PowerShell中Curl命令正常,PHP脚本调用Curl失败问题排查
BigCommerce API请求:PowerShell curl成功但PHP脚本失败排查
问题说明
我在PowerShell中运行curl命令可以成功获取BigCommerce API数据,但将其转为PHP脚本(命令行运行)时执行失败。
成功的PowerShell curl命令
curl.exe https://api.bigcommerce.com/stores/a1b2c3d4/v3/customers/attributes -H "x-auth-token: a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4" -H "Content-Type: application/json"
curl返回结果
{"data":[{"id":2,"name":"gp_customer_id","type":"string","date_created":"2021-12-14T14:18:10Z","date_modified":"2021-12-14T14:18:10Z"}],"meta":{"pagination":{"total":1,"count":1,"per_page":50,"current_page":1,"total_pages":1}}}
失败的PHP脚本代码
<?php $ACCESS_TOKEN = "a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4"; $STORE_HASH = "a1b2c3d4"; $headers = array(); $headers[] = "x-auth-token: $ACCESS_TOKEN"; $headers[] = 'Content-Type: application/json'; $headers[] = 'ACCEPT: application/json'; var_dump ($headers); echo "https://api.bigcommerce.com/stores/$STORE_HASH/v3/customers/attributes\n"; $state_ch = curl_init(); // curl_setopt($state_ch, CURLOPT_URL,"https://api.bigcommerce.com/stores/$STORE_HASH/v3/customers/attributes"); curl_setopt($state_ch, CURLOPT_URL,"https://api.bigcommerce.com/stores/a1b2c3d4/v3/customers/attributes"); curl_setopt($state_ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($state_ch, CURLOPT_HTTPHEADER, $headers); var_dump($state_ch); $state_result = curl_exec ($state_ch); var_dump($state_result); $state_result = json_decode($state_result); var_dump($state_result); ?>
PHP脚本执行结果
array(3) { [0]=> string(45) "x-auth-token: a1b2c3d4a1b2c3d4a1b2c3d4a1b2c3d4" [1]=> string(30) "Content-Type: application/json" [2]=> string(24) "ACCEPT: application/json"} https://api.bigcommerce.com/stores/a1b2c3d4/v3/customers/attributes resource(4) of type (curl) bool(false) NULL
排查建议
优先获取curl错误详情
在curl_exec后添加以下代码,直接打印错误信息,这是定位问题的核心:if(curl_errno($state_ch)){ echo 'Curl错误信息: ' . curl_error($state_ch); } curl_close($state_ch);常见问题排查方向
SSL证书验证问题:PHP curl默认会验证SSL证书,若本地CA不信任目标服务器证书,会导致请求失败。可临时添加以下参数测试(生产环境不建议长期禁用):
curl_setopt($state_ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($state_ch, CURLOPT_SSL_VERIFYHOST, false);若测试成功,建议更新本地CA证书库,而非禁用验证。
请求头一致性:原curl命令未显式发送
ACCEPT: application/json,可尝试从PHP脚本的headers数组中移除该条目,保持和原请求一致。网络配置差异:命令行curl和PHP可能使用不同的代理设置,检查PHP的
php.ini中是否存在curl.proxy配置,或在脚本中手动指定代理(若需):curl_setopt($state_ch, CURLOPT_PROXY, 'http://你的代理地址:端口');curl扩展状态:确保PHP已正确安装并启用curl扩展,可通过
php -m命令查看是否包含curl模块,或用phpinfo()检查curl配置细节。
内容的提问来源于stack exchange,提问作者Jimbus
相关产品推荐
相关产品推荐

