Search code examples
phpcssminify

Automatically replace first line in each file


I have a couple of minified files (CSS and JS) and I want to automatically replace the first line of each one (the first line of each file is something like Minified @ 2017-03-21) when I re-minify those files.

I'm currently adding that info in this way, but I accept suggestions:

<?php
$file = "test.css";
$add_info = "/* --- Minified today --- */ \n";
$add_info .= file_get_contents($file);
file_put_contents($file, $add_info);
?>

So my file ends like this:

/* --- Minified today --- */
body{margin:0}; /* etc */

And obviously after a couple repeats ends like this:

/* --- Minified today --- */
/* --- Minified today --- */
/* --- Minified today --- */
/* --- Minified today --- */
body{margin:0}; /* etc */

which isn't useful at all.

So, how can I do that (without killing performance)? That action will be performed just 1 o 2 times per week (as most), and the files are ~30KB after minify.

Note: I'm using PHP 5.5 and Apache 2.4.


Solution

  • You can read the file into an array with file() and replace the first line. Then file_put_contents() will implode the array for you:

    $file = "test.css";
    $lines = file($file);
    $add_info = "/* --- Minified today --- */ \n";
    $lines[0] = $add_info;
    file_put_contents($file, $lines);
    

    If they may not have that as a first line then check and either replace it or insert it:

    if(strpos($lines[0], '/* --- Minified') !== false) {
        $lines[0] = $add_info;
    } else {
        array_unshift($lines, $add_info);
    }