Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use curl with relative path in PHP?

Tags:

php

curl

I have two php pages. I want to fetch b.php in a.php.

In my a.php:

$ch = curl_init("b.php");
echo(curl_exec($ch));
curl_close($ch);

Doesn't work;

But:

$ch = curl_init("www.site.com/b.php");
echo(curl_exec($ch));
curl_close($ch);

is OK. I'm sure a.php is under www.site.com.

Why curl can't work with relative path? Is there a workaround?

like image 495
Lai Yu-Hsuan Avatar asked Jul 07 '11 19:07

Lai Yu-Hsuan


2 Answers

Curl is a seperate library which does not really know anything about webservers and where it's coming from or (philosophicaly) why it is there. So you may 'fake' relative urls using one of the two _SERVER variables:

$_SERVER['SERVER_NAME'] 

The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

$_SERVER['HTTP_HOST']

Contents of the Host: header from the current request, if there is one.

See: http://php.net/manual/en/reserved.variables.server.php

Edit update: I thought a moment longer about this: do you really need to fetch it with curl? You usually may also fetch any output of another script like this and save the overhead of loading it through a new http request:

ob_start();
require "b.php";
$output = ob_get_clean();
like image 178
Arend Avatar answered Oct 26 '22 12:10

Arend


How about taking the domain from HTTP_HOST?

$domain = $_SERVER['HTTP_HOST'];
$prefix = $_SERVER['HTTPS'] ? 'https://' : 'http://';
$relative = '/b.php';
$ch = curl_init($prefix.$domain.$relative);
echo(curl_exec($ch));
curl_close($ch);
like image 21
14 revs, 4 users 99% Avatar answered Oct 26 '22 10:10

14 revs, 4 users 99%