如何使用 php curl 为特定 IP 设置主机名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9932636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:56:31  来源:igfitidea点击:

How to set hostname using php curl for a specific ip

phpcurl

提问by Vishesh Joshi

Hi I have a server which has several virtual hosts set up on it.

嗨,我有一台服务器,上面设置了几个虚拟主机。

I wanted to make a curl request to this server's ip using php. Also I wanted to make this request to a specific hostname on the server's ip.

我想使用 php 向该服务器的 ip 发出 curl 请求。此外,我想向服务器 ip 上的特定主机名发出此请求。

Is there a way to do it?

有没有办法做到这一点?

A bit more elaboration : I want to make a curl requests between my servers using internal LAN, using their internal IP. The issue is that I have several sites hosted on this server. So when i make a curl request to the internal IP of the server.. something like (curl_init(xxx.xxx.xxx.xxx)), I want to be able to be tell apache to go to a particular folder pointed to by a virtual host. I hope that made the question a bit more clear.. – Vishesh Joshi 3 mins ago edit

更详细一点:我想使用内部 LAN 在我的服务器之间使用它们的内部 IP 发出 curl 请求。问题是我在这台服务器上托管了几个站点。因此,当我向服务器的内部 IP 发出 curl 请求时……类似于 (curl_init(xxx.xxx.xxx.xxx)),我希望能够告诉 apache 转到 a 指向的特定文件夹虚拟主机。我希望这能让问题更清楚一点.. – Vishesh Joshi 3 分钟前编辑

回答by simpleigh

You can set the host header in the curl request:

您可以在 curl 请求中设置主机标头:

<?php
$ch = curl_init('XXX.XXX.XXX.XXX');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: subdomain.hostname.com'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($ch);

回答by sanmai

For HTTPS sites use CURLOPT_RESOLVEwhich exists in every PHP version since PHP 5.5.

对于 HTTPS 站点,使用自 PHP 5.5 起CURLOPT_RESOLVE存在于每个 PHP 版本中的HTTPS 站点。

<?php
$ch = curl_init('https://www.example.com/');
// note: array used here
curl_setopt($ch, CURLOPT_RESOLVE, array(
    "www.example.com:443:172.16.1.1",
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);

Sample output:

示例输出:

* Added www.example.com:443:172.16.1.1 to DNS cache
* Hostname www.example.com was found in DNS cache
*   Trying 172.16.1.1...

回答by temple

Base on Leigh Simpson, It works, but I need query string attach with it. That's what I work around:

基于 Leigh Simpson,它可以工作,但我需要附加查询字符串。这就是我的工作:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://xxx.xxx.xxx.xxx/index.php?page=api&action=getdifficulty");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: subdomain.hostname.com'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($ch);
?>