Anam
Anam

Reputation: 12169

Dynamically include css or Js file using php

Every time Gulp changes the CSS or JS files it keep the output file name same as before. How will browser know that file has been changed and need to reload the css and JS files?

To resolve this problem, I am decide to use the following Gulp plugin:

https://github.com/sindresorhus/gulp-rev

it rename the assets file by appending content hash to filenames

unicorn.css => unicorn-098f6bcd.css

is there any way to include the assets file using php dynamically? Assets name will change every time when new content added.

Upvotes: 2

Views: 1214

Answers (2)

Anam
Anam

Reputation: 12169

I have found a way to include file dynamically. its fast (takes about 1.5 ms) and working perfectly.

PHP has a native function (glob) for searching files. According to PHP docs "The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells."

glob()

// css path would be the full physical path of your css directory
$cssPath = '/css/*.css';
$stylesheets = glob($cssPath, GLOB_NOSORT);

// link all stylesheets
<?php foreach($stylesheets as $stylesheet): ?>

     <link rel="stylesheet" href="css/<?=basename($stylesheet)?>">

<?php endforeach; ?>

Upvotes: 0

Amir Surnay
Amir Surnay

Reputation: 404

instead renaming file, you can send finger print with it. if file changes, last modified changes too. so you can easily use file's last modified as finger print:

public function putStyle($fileName)
{
    $fp = filemtime($fileName); // finger print by file last modified
    $fileName .= '?' . $fp;
    echo '<link rel="stylesheet" href="' . $fileName . '"/>';
}

Upvotes: 1

Related Questions