首页 > 解决方案 > 如何使用带有公共文件夹的 PHP 找到我的 CSS 链接的正确路径

问题描述

在开发我的网站时,我还会做一些小项目,这些项目会放入我的网站中。我想让我的项目部分链接到我的项目。我希望每个项目都有自己的 CSS 文件,这样我就没有一个非常庞大的文件。所以这是我的问题,我在找到链接我的 css 的正确路径时遇到了一些问题。

因为我使用 PHP,所以我有一个公用文件夹,其中主要的 index.php 用作简单的路由器。这是我的架构:

|img\
|-- some images
|public\ (docroot)
|--index.php
|--js\
|----index.js
|--style\
|----partials\
|-------_projet.scss
|----main.scss (with @import 'partials/projet')
|----main.css
|templates\
|--projet\
|----files for the project
|--all my templates like header.php, footer.php...

这是 public/ 中的 index.php :

<?php
require "../vendor/autoload.php";

$required = null;
$projet = null;
$title = 'KumaTeK';
$uri = $_SERVER['REQUEST_URI'];

switch($uri) {
    case '/' :
        $required = '../templates/home.php';
        break;
    case '/projets/projet1' :
        $projet = '../templates/projet1/index.php';
        $title = 'Projet1';
        break;
    default :
        $required = '../templates/404.php';
        break;
}


if ($required) {
    require '../templates/header.php';
    require $required;
    require '../templates/footer.php';
}

?>

在我的 header.php 中,我有:

<link rel="stylesheet" href="style/main.css">

哪个适用于 home.php(或路由的“/”)。但是当我转到 /projets/projet1 时,我有没有 CSS 的 HTML。

我想知道是否有一种技术可以找到正确的路径,或者我是否做错了什么。(我也有图像路径的问题。)

标签: phphtmlcss

解决方案


正如评论中所写,您必须写:

<link rel="stylesheet" href="/style/main.css">

这有什么不同

<link rel="stylesheet" href="style/main.css">

在第一种情况下,url 将始终与您的域名相关,这意味着即使您的 url 是http://localhost/projets/projet1,css url 也将是http://localhost/style/main.css(它与您当前的 url 无关)。

在第二种情况下,css url 将与您当前的 url 相关,这意味着即使您的 url 是http://localhost/projets/projet1,css url 也将是http://localhost/projets/projet1/style/main.css(它与您当前的 url 相关)。


推荐阅读