php - 动态获取文件路径
问题描述
我正在制作一个网站,并将 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";
?>
在我所有的页面上。
解决方案
将 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 定义路径
推荐阅读
- python - 如何为多个 matplotlib 绘图使用相同的 NavigationToolbar2Tk
- c# - Unity 自定义编辑器预制件显示修改后的值
- asp.net - 编辑按钮未显示在我的 ASPxGridView 中
- scala - 出现以下错误: java.lang.NoSuchMethodError: scala.Predef$.wrapRefArray([Ljava/lang/Object;)Lscala/collection/mutable/WrappedArray;
- c# - 可以在 C# 中使用具有 CA 证书的 .p12 文件而不将它们导入证书存储
- r - 如何使用 ggplot2 创建分组累积频率图
- c++ - 只读变量不可赋值
- c# - WPF - 通过单击适当的按钮将主题从暗变为亮 - Avalonia
- reactjs - 如何使用功能组件从子级读取和更新 React Context?
- firebase - 如何在flutter中从firebase cloud firestore查询数据