PHP包括来自外部服务器

时间:2014-07-17 02:05:49

标签: php

我想使用PHP“include”函数来包含来自与我的主脚本不同的域的文件,并使用包含文件中主脚本的变量。

这样的事情:

的index.php:

<?php
  $hello = "Hello";
  $world = "World";
  include "http://example.com/myfile.php";
?>

myfile.php (来自其他域名)

<?php
  echo $hello . " " . $world;
  // Should output "Hello World"
?>

这是否有效,还是取决于服务器设置/权限?

3 个答案:

答案 0 :(得分:1)

来自the manual

  

使用远程文件

     

只要在php.ini中启用了allow_url_fopen,就可以使用HTTP和FTP URL以及将文件名作为参数的大多数函数。此外,URL可以与include,include_once,require和require_once语句一起使用(因为PHP 5.2.0,必须为这些语句启用allow_url_include)。有关PHP支持的协议的更多信息,请参阅Supported Protocols和Wrappers。

答案 1 :(得分:1)

根据allow_url_include中是否启用php.ini,它会有效。否则,您可以通过将当前include行替换为:

来尝试以此方式执行此操作
echo file_get_contents('http://example.com/myfile.php');

答案 2 :(得分:1)

正如几个答案所指出的那样,allow_url_include必须启用,而且在我的情况下这不是一个选项。我最终这样做了:

的index.php:

<?php
  $hello = "Hello";
  $world = "World";
  echo file_get_contents("http://example.com/myfile.php?hello=$hello&world=$world");
?>

myfile.php(来自其他域名)

<?php
  $hello = $_GET['hello'];
  $world = $_GET['world'];
  echo $hello . " " . $world;
  // Should output "Hello World"
?>

它适用于我需要它做的事情,但我确信可以改进解决方案。