Thursday, September 1, 2022

[SOLVED] How to force cURL to send a complete URL as request target?

Issue

How does I force curl to include the complete URL in the HTTP GET request?

Curl sends (not working):

GET /some/path HTTP/1.1
Host: my-domain-here.com
...

I want it to be (working):

GET http://my-domain-here.com/some/path HTTP/1.1
Host: i2.wp.com

So I want the host to be always included in the GET line. How can I do this using CURL/PHP? The server can only handle absolute URLs.


Solution

The PHP cURL wrapper does not expose a way of doing this as far as I know.

Also, cURL will automatically change the Host header even if you specify a different one. For example:

curl -v --dump-header - -0 -H 'Host: my-domain.com' http://subdomain.my-domain.com/something.html

will ignore the custom header and send this:

GET /something.html HTTP/1.0
User-Agent: curl/7.35.0
Host: subdomain.my-domain.com
Accept: */*

What you can do is build the request manually:

$host = 'my-domain.com';
$path = 'http://subdomain.my-domain.com/something.html';

$fp = fsockopen($host, 80);

fputs($fp, "GET $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: 0\r\n");
fputs($fp, "Connection: close\r\n\r\n");

$result = ''; 
while(!feof($fp)) {
    $result .= fgets($fp, 128);
}

fclose($fp);

echo $result;


Answered By - Sergiu Paraschiv
Answer Checked By - Clifford M. (WPSolving Volunteer)