Keefer
Keefer

Reputation: 2289

Relative PHP Paths for file_get_contents

This seems like a simple and common task, but we cannot get it to work:

We've got two of us working on a project and both have our machines setup as local servers, with a production environment eventually.

In the head of all of our project we've got PHP Like the following:

$feed = "/lib/php/backend/gateway.php?action=history";
$json = file_get_contents($feed, true);

Only way to get it to work is to set it as a full URL like http://dev01.domain.com/lib/php/backend/gateway.php?action=history or by setting it up as localhost like this:

$feed = "http://localhost/lib/php/backend/gateway.php?action=history";
$json = file_get_contents($feed, true);

The latter obviously works on our local boxes and presumably would work in production as well, but is there a way to use relative paths to be a bit cleaner?

Upvotes: 6

Views: 13045

Answers (2)

ajreal
ajreal

Reputation: 47331

convert the /lib/php/backend/gateway.php?action=history into a function/class-method

eg.

function gateway($action)
{
  // existing code
}
$json = gateway('history');

further more, there is no-need to spawn another HTTP process
(which is file_get_contents in this case)

Upvotes: 2

Dan Grossman
Dan Grossman

Reputation: 52372

$feed = 'http://' . $_SERVER['HTTP_HOST'] . '/lib/php/backend/gateway.php?action=history';

When you tried this --

$feed = "/lib/php/backend/gateway.php?action=history";
$json = file_get_contents($feed, true);

Realize that you are asking PHP to open a file at that path on your computer. Files do not have query strings, and the result would be the PHP code in that file, not the result of executing it.

When you ask for http://localhost/...., you're asking PHP to open a URL, making an HTTP request to a web server which executes the code and returns the output of that code.

Very different.

In reality though, why don't you incorporate the code in gateway.php into your current file? There's no reason to make an HTTP request to execute code on your own server.

Upvotes: 12

Related Questions