Skip to content
Advertisement

PHP function that auto imports all CSS files from a certain directory

I’m working on a website that has 6 CSS files at the moment. I want to make a php function that scans a directory and load all the CSS files in de HTMl head. I got this working on the index page, but as soon as I go to another page it doesn’t work. This is because it’s searching for the CSS folder from an different location. To be clear, In the root folder I have a file called Header.php, index.php and Footer.php . The header.php file contains the HTML head and the navigation bar/menu at the top of the website. The header.php is loaded in every page with this line

require "header.php"; 

The file path changes on a higher laying page, for example the one on in the “About Us” page look like this

require "../../header.php";

I can solve the problem bye making the function for every sup directory, but this isn’t the correct way to do it (at least I think). This is my current php function:

function css(){
    $css = glob("CSS/*.css");
    $css_out = "";
    foreach($css as $css_path){
        $css_out .= '<link rel="stylesheet" href="'.$css_path.'">'; 
    }
    return $css_out;
}

I have this at the top of the page just bereave the require header

$css_web = css();

I load the actual data with

 <?php echo $css_web?>

Advertisement

Answer

Use absolute URL instead of relative URL.

Replace

$css_out .= '<link rel="stylesheet" href="'.$css_path.'">';

with

//$assets_url = "http://example.com/assets/css/";
$css_out .= '<link rel="stylesheet" href="'.$assets_url.'.'.$css_path.'">';
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement