如何在服务器根文件夹(PHP)中管理和构建页面和链接


How to manage and structure pages and links in server root folder (PHP)

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

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

在我的index.php页面中,我添加了类似的标题

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

在我的page.php页面中,它位于根文件夹中的info文件夹中,如c:''examplep/htdocs/website/info

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

所有这些都很好,但当heeader内的图像路径保持不变时,问题就会出现,即图像路径适用于index.php文件,但不适用于page.php文件,原因你已经知道了。

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

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

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

当我用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");

我就是这么做的。。。

在您创建的每个新页面的顶部设置变量,并在您的页面和任何include中设置这些变量。

// 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>';

这是您的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,就不会再有任何问题了。