Pages

Curl Request with custom IP and hostname (in php)

There could be following instances you might encounter while doing curl!

Scenarios 
  1. If host-name used in RequestURL, is not in public domain.
  2. If you are trying to avoid load balancer routing, while curling to a local domain. 
  3. If single server serves multiple hostnames, and hostnames are not yet registered. 
Here is what you have to do!!
  1. Curl with url by IP-Address. (that might return 400 error if server is serving multiple domain.)
  2. To solve this include host in HTTP header. 
How To do it?

In PHP

$ipaddress='10.14.9.7';
$url='path/to/file?';
$session = curl_init('http://'.$ipaddress.$url);
$headers = array("Host: ".$http_host);     
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
curl_setopt($session, CURLOPT_TIMEOUT, $timeout);
$content = curl_exec($session);
echo $content

This how to get local ip and hostname in php
$ipaddress=$_SERVER['SERVER_ADDR'];
$hostname=$_SERVER['HTTP_HOST'];


In command line curl 
 curl "http://10.14.9.7/path/to/file" -H "Host: myhostname.com"


No comments:

Post a Comment

Your comment will inspire me, Please leave your comment