【问题标题】:How to manage and structure pages and links in server root folder (PHP)如何管理和构造服务器根文件夹中的页面和链接 (PHP)
【发布时间】:2014-11-23 14:31:45
【问题描述】:

我没有使用任何框架,只是在 XAMPP 环境中工作。

我也有一个索引文件 index.php,最重要的是我想为我的所有页面添加相同的标题。

在我的 index.php 页面中,我添加我的标题,如

<?php include 'html/headers/header.html'; ?>

在我的 page.php 页面中,该页面位于根文件夹中的 info 文件夹内,例如 c:/xampp/htdocs/website/info

<?php include '../html/headers/header.html'; ?>

一切正常,但是当标题内的图像路径保持不变时会出现问题,即图像路径适用于 index.php 文件但不适用于 page.php 文件,原因你已经知道了。

我试过$_SERVER['DOCUMENT_ROOT']."/website/images/logo.png". 既没用也不想要这种技术,因为页眉和页脚等中可能有很多图像。

我也不想使用任何框架或 CDN 存储。

这个问题能轻松解决吗?如果我错过了什么,请告诉我。谢谢

【问题讨论】:

  • @DanFromGermany 只需编辑问题
  • 在 index.php 中包含标题。在那里你加载不同的页面,比如带有 GET[] 参数的信息?简单、快速、轻便。
  • @Zafta 我应该给你发一些代码,你明白我的意思吗?

标签: php xampp include-path document-root


【解决方案1】:

当我在 PHP 中编码时,我倾向于在每个 PHP 文件的开头有两个变量。

// Use for file on the server, eg includes
$file_path = "../";

// For files relative to my page path, eg images, links
$link_path = "../../";

我会根据文件的位置更改其中的每一个。

然后我在任何包含前面加上$file_path,并在页面上的东西(例如图像、超链接)前面加上$link_path

echo '<img src="' . $link_path . 'images/myimage.png" />';
include ($file_path . "html/headers/header.html");

反正我就是这么干的……

在您创建的每个新页面的顶部设置变量,并将它们包含在您的页面和任何包含中。

// New file
$file_path = "../";
$link_path = "../../";

include($file_path . "html/headers/header.html");

然后在你的 header.html 和页面中,你会去:

echo '<img src="' . $link_path . 'website/images/logo.png" />';

如果你想要一个链接,你会去:

echo '<a href="' . $link_path . 'website/page.html'>My Link</a>';

【讨论】:

  • header.html 文件中的图片无法显示,导致 index.php 给出了 img src !
  • 这就是为什么您会在包含的文件中使用$link_path 来处理图像。确保每个文件都有正确的路径。
  • 比 index.php 不工作!两个不同的链接路径,只有 1 个文件
  • @Coulton 总是使用它是高效且良好的技术吗
  • @Zafta 好问题,可能不是,但它是一个简单的解决方案,可确保您的网址正确
【解决方案2】:

这是你的 index.php 页面

<?php
    if(isset($_GET['page'])) {
        $dir = 'page/' . $_GET['page']. '.php';
        if(file_exists($dir)) {
            include_once($dir);
        } else {
            include_once('page/404.php');
        }
    } else {
        include_once('page/home.php');
    }
?>

你有一个这样的文件夹结构

  • 章节
  • index.php

在您保存 home.php、info.php 等的页面中。 并在部分中保存 header.php、footer.php 等。

比你使用 index.php 中的图像 src 更没有问题了。

【讨论】:

  • 很好,但是基于 GET 变量显示实体总是有效的吗??
猜你喜欢
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 1970-01-01
相关资源
最近更新 更多