【问题标题】:PHP sometimes relative links work sometimes they don't?PHP 有时相对链接有时不工作?
【发布时间】:2015-01-20 07:39:24
【问题描述】:

好的,这是我的项目结构(简化):

+blog
  -index.php //Index 2
  + views
    -index.php // Index 3
    -article.php
-index.php // Index 1
+partials
  -constants.php
  -top.php

好的,所以在 Index 1Index 2 我使用这行代码来包含一些部分/sn-ps:

索引 1

<?php require_once("./partials/constants.php"); ?>
<?php require_once("./partials/top.php"); ?>

索引 2

<?php require_once("../partials/constants.php"); ?>
<?php require_once("../partials/top.php"); ?>

但在 Index 3 如果我使用这个:

<?php require_once(".../partials/constants.php"); ?>
<?php require_once(".../partials/top.php"); ?>

我收到此错误:

<body><br>
<b>Warning</b>:  require_once(.../partials/constants.php): failed to open stream: No such file or directory in <b>/home/codio/workspace/blog/views/index.php</b> on line <b>1</b><br>
<br>
<b>Fatal error</b>:  require_once(): Failed opening required '.../partials/constants.php' (include_path='.:/home/codio/.parts/packages/php5-apache2/5.5.15/lib/php') in <b>/home/codio/workspace/blog/views/index.php</b> on line <b>1</b><br>
</body>

【问题讨论】:

    标签: php directory structure require relative-path


    【解决方案1】:

    文件路径前的点不代表目录的层级。

    ./引用你所在的同一个目录

    ../ 上一级。

    也就是说,您应该在 index3 上运行 ../../partials/constants.php

    对于index2,由于是index3的上一级,需要将require语句改成../partials/constants.php

    对于索引,因为它位于同一级别的目录 partials 中,您将运行 require ('partials/constants.php');

    【讨论】:

    • YOU BEAUTY 干杯,我从来不知道 :)
    • 虽然现在在关于 Index 2 的页面上我得到了这个错误:{"type":64,"message":"require_once(): Failed opening required '..\/..\/partials\/constants.php' (include_path='.:\/home\/codio\/.parts\/packages\/php5-apache2\/5.5.15\/lib\/php')","file":"\/home\/codio\/workspace\/blog\/views\/index.php","line":1}
    • 那是因为index2,只是里面的一个level,所以index2要使用../partials/constants.php
    • 正在这样做,但实际上并没有给我们带来压力:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多