首页 > 解决方案 > 动态获取文件路径

问题描述

我正在制作一个网站,并将 HTML 的所有内容移至<head>header.php 文件,在该文件中链接到我的样式表等。

在我的其他页面上,我包含了这个文件。但是当我将它包含在子文件夹中的页面中时,样式表的链接不再正确,我通过复制链接并添加解决了它../我想知道是否有更好的方法来做到这一点?喜欢动态获得正确的路径?在不使用绝对路径的情况下,就像我希望能够移动项目文件夹并让它仍然工作一样。

头文件.php

<?php
session_start();
?>

<!DOCTYPE html>
<html lang="nb" dir="ltr">  
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
  
    <!-- CSS -->
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet"  type="text/css" href="./css/style.css?<?php echo time(); ?>">
    <link rel="stylesheet"  type="text/css" href="../css/style.css?<?php echo time(); ?>">
    <link rel="stylesheet"  type="text/css" href="../../css/style.css?<?php echo time(); ?>">

    <!-- Title -->
    <title>Inventar</title>
</head>
<body>
    

然后我有:

<?php
include "header.php";
?>

在我所有的页面上。

标签: phphtml

解决方案


将 header.php 更改为

<?php
session_start();
?>

<!DOCTYPE html>
<html lang="nb" dir="ltr">  
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
  
    <!-- CSS -->
    <link rel="stylesheet" href="<?=$tempPath;?>/css/reset.css">
    <link rel="stylesheet"  type="text/css" href="<?=$tempPath;?>/css/style.css?<?php echo time(); ?>">
    <!-- Title -->
    <title>Inventar</title>
</head>
<body>

每当您包含添加路径时,请定义变量

<?php
 $tempPath="../";//like this add path according to the file
include "header.php";
?>

此外,如果需要,您可以使用dirname(__FILE__),以便您可以从 header.php 定义路径


推荐阅读