动态包含包含js和css资源的header.php文件

动态包含包含js和css资源的header.php文件,php,html,Php,Html,我有一个关于使用PHP包含头文件的问题 上面的代码是我在所有HTML/PHP视图文件中包含的头文件。我想将其保存在一个名为命名约定header.php的文件中 我怀疑的是资源负载 如果标题包含在另一个文件夹中,而该文件夹与保存css和js主文件夹的文件夹不同,那么如何加载所需的样式表和js文件? 我希望避免基本资源的重复,并避免由于资源文件的位置而出现控制台错误 <!DOCTYPE html> <html lang="it"> <head> <!-- b

我有一个关于使用PHP包含头文件的问题

上面的代码是我在所有HTML/PHP视图文件中包含的头文件。我想将其保存在一个名为命名约定
header.php的文件中

我怀疑的是资源负载

如果标题包含在另一个文件夹中,而该文件夹与保存css和js主文件夹的文件夹不同,那么如何加载所需的样式表和js文件?

我希望避免基本资源的重复,并避免由于资源文件的位置而出现控制台错误

<!DOCTYPE html>
<html lang="it">
<head>
<!-- basic meta tag -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<!-- add facebook og tag here -->
<meta property="og:url" content="" />
<meta property="og:type" content="article" />
<meta property="og:title" content="" />
<meta property="og:description" content="" />
<meta property="og:image" content="" />
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' https://masserianobile.it; font-src 'self' https://fonts.gstatic.com/; img-src 'self'; style-src 'self' https://fonts.googleapis.com/;">  -->

<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/fontawesome-all.min.css" type="text/css">
<link rel="stylesheet" href="css/app.min.css" type="text/css">

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src=""></script>

</head> 

以下是我用来为任何嵌套目录自动加载PHP类的方法,这也适用于您的前端资源:

<?php

/* the root directory of your project
   can be useful when working on local env
   must not end with a slash, leave it empty if not needed */
const ROOT_PATH = '/projects/some_stuff';

// Get parts of the URL without the root path
$rel_path = explode('/', str_replace(ROOT_PATH, '', $_SERVER['SCRIPT_NAME']));

// Remove empty items from the parts
$rel_path = array_filter($rel_path);

// If the last part is a php file, remove it, we don't need it
if (strpos(end($rel_path), '.php') !== false) { array_pop($rel_path); }

// Build the "../" prefix
$prefix = implode('/', array_fill(0, count($rel_path), '..'));
$prefix = empty($prefix) ? '' : $prefix . '/';

?>

<!-- just output the prefix before the resource URL -->
<link rel="stylesheet" href="<?php echo $prefix; ?>css/bootstrap.min.css" type="text/css">

看,只要把你的
放在页面中,重要的是你把它放在哪里,而不是放在哪里。我知道
包含
功能是如何工作的,我说的是页面资源,如果我把头文件放在页面中,而不是放在站点根目录下的文件夹中,由于文件夹的位置不同,它不会加载css和js文件。您想为资源自动添加前缀吗?是的,我想避免编辑头文件以匹配资源文件夹。我将尝试使用您的脚本!我正在使用
ob_start()
ob_get_clean()
export()
函数加载头模板文件,并在需要时更改路径。告诉我它是否有效,但应该有效,我在PHP7的生产服务器上使用它,没有任何问题。并确保
根路径
是资源文件夹的父目录(或空字符串)。