简体   繁体   中英

Include the header on all the pages in PHP

I am building a website and I am working with PHP. I have created a file named header.php (contains the header that needs to be included on all my page).

Let me use the content of my file header.php to explain myself better.

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Fashion</title> <link rel="stylesheet" href="css/header.css"/> <link rel="stylesheet" href="css/slider.css"/> <link rel="stylesheet" href="css/bloc-page.css"/> <!--Load it when the user is on the page clothes.php--> <link rel="stylesheet" href="css/footer.css"/> <link rel="stylesheet" href="css/header-search.css"/> <link rel="stylesheet" href="css/back-to-top.css"/> <link rel="stylesheet" href="css/form-register.css"> <!--Load it when the user is on the page register.php--> <link rel="stylesheet" href="css/form-login.css"> <link rel="stylesheet" type="text/css" href="css/style-carousel.css" /> <!--Load it when the user is on shoes.php--> <link rel="stylesheet" type="text/css" href="css/owl.carousel.css" /> <link rel="stylesheet" type="text/css" href="css/owl.theme.default.min.css" /> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/form-register.js"></script> <script src="js/modernizr.js"></script> <!-- Modernizr --> </head> 

The problem I am facing is that, I want to load certains CSS files when I am on certains pages. For example, I want to load the file bloc-page.css when the user is on clothes.php

I was thinking about using regular expression but I wanted to know if there is a better way of doing that.

Thanks for replying

You could make an array of all nessecary addon-css before you include header.php

<?php
$addonCss = Array("bloc-page.css");
include "header.php";
//... rest of page
?>

then check if there is such an array in header.php:

<?php
//....
if(isset($addonCss)) {
     for($i=0;$i<count($addonCss); $i++) {
         echo "<link rel=\"stylesheet\" href=\"css/".$addonCss[$i]."\"/>\n";
     }
}
//...
?>

This is just one (for here easiest) of many possibilities.

Make a base url and insert it all src, like

$base_url="mydomain.com";
<link rel="stylesheet" href="<?php echo $base_url ?>css/header.css"/>   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM