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?
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.
file_get_contents() is slightly faster than cURL.
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.
$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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With