Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative PHP Paths for file_get_contents

Tags:

php

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?

like image 325
Keefer Avatar asked Aug 10 '11 17:08

Keefer


People also ask

What does file_get_contents do in PHP?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string.

Which is faster cURL or file_get_contents?

file_get_contents() is slightly faster than cURL.

What is the difference between file_get_contents () function and file () function?

The file_get_contents() function reads entire file into a string. The file() function reads the entire file in a array, whereas file_get_contents() function reads the entire file into a string.


2 Answers

$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.

like image 83
Dan Grossman Avatar answered Oct 17 '22 08:10

Dan Grossman


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)

like image 25
ajreal Avatar answered Oct 17 '22 07:10

ajreal