Reputation: 55
I'm trying to open a socket on a host using the following code:
$timeout = 10;
$s = stream_socket_client('mywebsite.com:80', $errcode, $errstring, $timeout);
$message = "GET /index.php HTTP/1.0\r\n\r\n";
fwrite($s, $message);
while(!feof($s)){
echo fread($s, 1024);
}
Nothing fancy, just an example I found. The problem is that every time I run the code I get different files. I think this is because the host is a shared one.
Is there a way to overcome this problem, that is, pull reliably the proper file I'm trying to get?
Thank you.
Upvotes: 4
Views: 877
Reputation: 92792
You need to send the Host
header to specify the domain name - it is very common for one server to host multiple websites:
$message = "GET /index.php HTTP/1.1\r\nHost: www.example.com\r\n\r\n";
Note (as @Darhazer points out) that Host
request header is only defined since HTTP/1.1, so you can't use it wtih HTTP/1.0. There is a possibility to use the absolute URL, as in
$message = "GET http://www.example.com/index.php HTTP/1.0\r\n\r\n";
but this is a violation of HTTP/1.0:
The absoluteURI form is only allowed when the request is being made to a proxy.
and the target server apparently isn't a proxy, so the resulting behavior is unreliable.
Upvotes: 1
Reputation: 96346
in the HTTP request you have to specify which host you're accessing. as you noted correctly multiple DNS entries can point to the same IP address.
$message = "GET /index.php HTTP/1.1\r\nHost: hostname.com\r\n\r\n";
Upvotes: 3