Reputation:
I have a question about the inclusion of an header file using PHP.
The code above is the header that I include in all my HTML/PHP view files. I want to save it inside a file called as a naming convention header.php
.
My doubt is about the resources loading.
How I can load the needed stylesheets and js files if the header is included from another folder that isn't the same that hold the main css and js folders?
I want to avoid the duplication of the basic resources, and avoid having console errors due to the position of the resources files.
<!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>
Upvotes: 2
Views: 534
Reputation: 7539
Here is what I use to autoload my PHP classes for any nested directory, this can work for your Front-End resources too:
<?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">
Documentation:
$_SERVER
Server and execution environment informationarray_filter()
Filters elements of an array using a callback functionend()
Set the internal pointer of an array to its last elementarray_pop()
Pop the element off the end of arrayarray_fill()
Fill an array with valuesUpvotes: 1