php - Php Curl 不能只在一个网站上工作
问题描述
我有一个非常奇怪的错误。我需要使用 cURL 访问这个网站:http : //sub.example.com/。从本地主机我没有问题,如果我从命令行或浏览器使用 cURL 访问网站。
我在我的 Siteground 服务器上使用此代码:
<?php
$url="http://sub.example.com/";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);
?>
我得到$result = false。
如果我使用 Try / Catch 我得到:Curl failed with error #6: Could not resolve host
我还尝试将 $url 替换为另一个网站的 url,它始终有效(http 和 https,域和子域,在我的服务器和外部)!
我已经花了一天时间试图解决这个问题,请帮助我!
提前谢谢你,卢卡
解决方案
根据googledns,sub.example.com
不存在。
$ nslookup sub.example.com 8.8.8.8
*** google-public-dns-a.google.com can't find sub.example.com: Non-existent domain
Server: google-public-dns-a.google.com
Address: 8.8.8.8
它在 localhost 上为您工作的事实意味着您有一个奇怪的 DNS,或者可能在您的hosts 文件中有一个条目,而您的 Siteground 服务器没有。
无论如何,Curl failed with error #6: Could not resolve host
这意味着服务器的 dns 找不到sub.example.com
,但幸运的是,如果您知道要连接的 ip,则可以完全绕过 DNS,而是编写:
curl_setopt($ch, CURLOPT_URL,'http://93.184.216.34/');
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Host: sub.example.com'));
(还有一个更正确的 curlopt 来告诉 curl 哪个 ip 与哪个域一起使用,但是这个名字现在让我无法理解,而且 iirc、php 还没有添加对它的官方支持,所以你必须使用它的魔法值,而不是定义的名称,但手动设置Host:
标题还是很容易的)
推荐阅读
- c++ - 如何在 C 或 C++ 中将字符转换为整数
- bash - 在 bash 别名设置中指定输入参数的范围
- php - $_SESSION 变量未设置值
- html - 通过共享网站链接共享信息
- android - 从广播接收器在 AlarmManager 事件上启动 Activity
- java - 如何根据日期对“MMM YYYY”日期字符串进行排序?
- javascript - 为什么我的 Chrome 扩展在性能分析期间更快?
- javascript - 如何将“标题”和“艺术家”发送到外部 xml 文档?
- javascript - 带有 Next.js 11 脚本的 TruConversion 热图脚本
- vb.net - 在包含结构的模块中创建表