如果是index.php,显示“this”,如果不是,显示“this”


If index.php, show "this", if not, show "this"

迫切希望有人能帮助这个。我是php的新手。我试着通过教程自学,我到处找都没用。

基本上我想实现一个"如果index.php页面,显示foo,如果不在index.php页面,显示bar"

任何想法?

我希望我解释得足够好…

index.php包含一个侧边栏:

require_once('./cache/templates/sidebar.php');

每个后续页面都使用index.php文件中定义的内容构建,这意味着sidebar.php是必须的。

我想编辑sidebar.php包含一个广告,仅显示在索引页。

现在,当我编辑sidebar.php时,例如,要显示字母"B",它将显示在主页上,以及其他类似的页面;

索引页:http://img.photobucket.com/albums/v684/nilsatis/1stack.jpg

每隔一页:http://img.photobucket.com/albums/v684/nilsatis/2stack.jpg

如何规定包含文件的一个区域显示在一个页面上,而不显示在其他页面上?

任何帮助都将是非常感激的。

[编辑]这是问题的网站:www.grandoldteam.com。您可以看到我在sidebar.php中输入了文本"Test"。我希望这段文字(未来的广告)只出现在索引页上,不在其他地方。

[Edit 2]这是index.php文件中调用sidebar.php的地方;

<p class="page_desc">'.$PAGE['subtitle'].'</p>
' );
            }
            if (isset($url[1])) require_once('./cache/html/'.$url[0].'/'.$url[1].'.php');
            else require_once('./cache/html/'.$url[0].'.php');
        }
    }
    require_once('./cache/templates/sidebar.php');

}

require_once('./cache/templates/footer.php');

我可以在这里编辑sidebar。php来显示想要的文本;

<div class="clear"></div>
test
        </div>
<p>
    </div>

要按您想要的方式做,请使用$_SERVER超全局变量。脚本的名称出现在多个地方。

if (strpos($_SERVER['SCRIPT_NAME'], 'index.php') !== false) // index page...

另一个选择是让index.php在包含侧栏之前设置一些变量,如$show_ad,并且侧栏页面可以检查该变量

我不建议检索调用脚本的名称,因为多个页面可能在不同的文件夹中具有相同的名称,也因为您可能希望在将来更改页面名称。

使用全局变量或常量来说明哪个页面是调用者。

index . php:

<?php
  $GLOBALS['caller_page'] = 'index';
  require_once('./cache/templates/sidebar.php');
  ...

sidebar.php:

<?php
  ... 
  if ( isset($GLOBALS['caller_page']) && ($GLOBALS['caller_page']=='index') ) {
    ... // special action for the index page 
  }
  ...

试试这个,

在你只想显示"foo"的页面上创建一个会话

然后执行

if ($_SESSION['valid']) {
//if the session is present, then show
}
else {
//if not,
}

这不仅是一个更好的方式去做,如果你的文件名被改变了会发生什么?这样一来,它就无关紧要了,因为它检查的是会话,而不是可能改变的东西:)

所有这些答案都很好,但我提供了一个不同的实践。它不是更好,但在我看来更舒服。

require_once('./cache/templates/sidebar.php');

在index.php上,这样做:

require_once('./cache/templates/sidebar.php?ad=1');

现在,在sidebar.php中添加:

if(isset($_GET['ad'])&& $_GET['ad']=='1')
 // display ad
else
//don't display ad
编辑:

你想要工作代码,好的…

假设你的广告实际上是stackoverflow徽标的图像:

现在在sidebar。php中你会看到这样的内容:

<?php
....

if(isset($_GET['ad'])&& $_GET['ad']=='1')
  {
 ?>
<div>
<a href="http://stackoverflow.com">
<img src="http://blog.vicompany.nl/wp-content/uploads/2011/04/stackoverflow-logo-250.png" alt="ad"/>
</a>
</div>
<?php
} 
else
{
}
....
?>

如何计算:

在sidebar.php的顶部,添加一行:

print_r($_SERVER);

这将显示$_SERVER变量的完整内容。由此,您应该看到一些可以使用的候选项,以及其他可能在某些时候对您有用的东西。

一旦你决定使用什么,你需要检查它是否包括字符串index.php。一个好的方法是使用:

if (strpos($_SERVER['SCRIPT_NAME'], 'index.php') !== false) {
}

这一行检查字符串index.php在脚本名中的位置是否为false,即它是否为一个值。

测试值

$_SERVER[ 'REQUEST_URI' ]

与文字

比较

/index . php的。

如果是相同的。你的index.php正在执行