Reputation: 19733
I have a very basic PHP file on a separate server (server 1) that literally contains the following:
<?php $version = "1.0.0"; ?>
In my PHP file on server 2, what I would like to do it simply echo this variable. I have tried using get_file_contents()
but I think this is for files on the same server. So I also tried using something similar but also using fopen()
and this resulted in Resource id #93.
Looking around on Google, I have found so many different examples, but I basically want to have a short and simple one. Can anyone point me in the right direction?
Upvotes: 2
Views: 2512
Reputation: 1001
Server 1:
<?php
$version = "1.0.0";
echo $version;
Server 2:
<?php
$version = file_get_contents('http://server1.com/script.php');
(thats assuming server 1 is web accessible from server 2)
Edit: Following on from a comment, should you wish to access more than one variable, you could use this:
Server 1:
<?php
$version = "1.0.0";
$name = 'this is my name';
echo json_encode(compact('version','name'));
Server 2:
<?php
$data= json_decode(file_get_contents('http://server1.com/script.php'),true);
echo 'my version is:'.$data['version'];
That should be fairly self explanatory - any questions via comments..
Upvotes: 3
Reputation: 429
file_get_contents only works to read the output of a file, and the example that you are showing doesn't have any kind of output. If you really want to do this you should echo some kind of data so that your can be able to fetch it with get_file_contents.
Another aproach is to include() it, but this is a big security flaw and php.ini disallows this option by default.
Mabe this works for you, instead of the code above you should do something like
<?php echo "1.0.0"; ?>
Then somewhere else you could do this:
<?php
$path = "http://www.somepage.com/version.php";
$version = file_get_contents(urlencode($path));
?>
But be aware that you need to modify your php.ini if you want file_get_contents to work on remote files. You will need to modify the directive allow_url_fopen to true.
Upvotes: 1
Reputation: 7362
Is the PHP file on the remote server hosted on a webserver like apache?How is it hosted? You can try using curl
$url = "http://<ip_or_domain_of_remote_server>/your_file.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
$result = curl_exec($ch);
echo $result
You should also ensure that your ports are open on the remote server and your file has the appropriate permissions
also, with curl, you can pass variables to the remote php script like this:
$url = "http://<ip_or_domain_of_remote_server>/your_file.php";
$data = array("key0"=>"val0","key1"=>"val1");
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
echo $result
Upvotes: 0