2

別のサーバー(サーバー1)に非常に基本的なPHPファイルがあり、文字通り次のものが含まれています。

<?php $version = "1.0.0"; ?>

サーバー2のPHPファイルで、この変数をエコーするだけです。使ってみget_file_contents()ましたが、同じサーバー上のファイル用だと思います。だから私も似たようなものを使ってみましたがfopen()、これも使ってリソースID#93になりました。

グーグルを見回してみると、いろいろな例がありますが、基本的には短くてシンプルなものが欲しいです。誰かが私を正しい方向に向けることができますか?

4

3 に答える 3

3

サーバー1:

<?php
$version = "1.0.0";
echo $version;

サーバー2:

<?php
$version = file_get_contents('http://server1.com/script.php');

(サーバー1がサーバー2からWebアクセス可能であると想定しています)


編集:コメントに続いて、複数の変数にアクセスしたい場合は、これを使用できます:

サーバー1:

<?php
$version = "1.0.0";
$name = 'this is my name';
echo json_encode(compact('version','name'));

サーバー2:

<?php
$data= json_decode(file_get_contents('http://server1.com/script.php'),true);
echo 'my version is:'.$data['version'];

それはかなり自明のはずです-コメントによる質問。

于 2013-03-07T00:04:20.863 に答える
1

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.

于 2013-03-07T00:12:24.843 に答える
0

リモートサーバー上のPHPファイルはapacheのようなWebサーバーでホストされていますか?どのようにホストされていますか?カールを使ってみることができます

$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

また、リモートサーバーでポートが開いていて、ファイルに適切な権限があることを確認する必要があります

また、curlを使用すると、次のように変数をリモートphpスクリプトに渡すことができます。

 $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
于 2013-03-07T00:05:41.977 に答える