使用Include,require,file_get_contents,readfile获取$ _SERVER

时间:2014-08-11 07:38:40

标签: php

为什么每当我使用include,require,file_get_contents或readfile获取$ _SERVER ['SERVER_NAME']时,它会给我一个不同的结果?

file1.php
网站:example1.com

<?php
  //sample code inside this file

  $_SERVER['SERVER_NAME'];
?>

file2.php
网站:example2.com

<?php
  require("example1.com/file1.php"); //result: example1.com

  //my expected result is example2.com
?>

我在file2.php中的预期结果是 example2.com ,但它只显示example1.com而不是example2.com。为什么$ _SERVER只能在另一方工作,并且在假设只是获取代码时没有按预期工作?


只是为了让一切都清楚:

这是一个例子:
example1.com
file1.php
在file1.php里面是$ _SERVER ['server_name'];


example2.com
包括example1.com/file1.php


example3.com
包括example1.com/file1.php


我想要发生的是使用集中文件(来自example.com的file1.php)在他们自己的网站上显示每个网站URL

但问题是每个网站都显示 example1.com 而不是自己的网站网址。

2 个答案:

答案 0 :(得分:1)

您可以使用:$ _SERVER [&#39; HTTP_HOST&#39;]。$ _ SERVER [&#39; REQUEST_URI&#39;];

网站:<强> www.example-one.com 文件:<强> linkone.php

<?php 
$addrone = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>

网站:<强> www.example-two.com 文件:<强> linktwo.php

<?php
    include_once 'www.example-one.com'; // Adds $addrone;
    $addrtwo = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>

<!DOCTYPE html>
<html>
<head>
    <script>
    document.onreadystatechange = function()
    {
        if(document.readyState == "complete")
        {
            var onex = document.getElementById("one");
            var twox = document.getElementById("two");
            onex.onclick = function()
            {
                alert("<?php echo $addrone; ?>");
            }
            twox.onclick = function()
            {
                alert("<?php echo $addrtwo; ?>");
            }
        }
    }
    </script>
</head>
<body>
    <button id="one">one</button>
    <button id="two">two</button>
</body>
</html>

希望这有帮助。

答案 1 :(得分:0)

使用require("example1.com/file1.php"); //result: example1.com您不需要代码。您需要执行代码的结果。如果您包含代码本身,只需将file1.php重命名为file1.txt