when we use Expires header for text files like js, css, contents are cached in the browser, to get new content we need to change in the html file the new names in the link and script tag. When we add changes. How can we automate it.
In a Windows Box, I may have some bunch of html files in multiple folders also in subdirectories.
There would be a text file
filelist.txt
OldName NewName
oldfile1-ver-1.0.js oldfile1-ver-2.0.js
oldfile2-ver-1.0.js oldfile2-ver-2.0.js
oldfile3-ver-1.0.js oldfile3-ver-2.0.js
oldfile4-ver-1.0.js oldfile4-ver-2.0.js
The script should change all the oldfile1-ver-1.0.js into oldfile1-ver-2.0.js in the html, php files
I would run this script before i start uploading.
Finally the script could create a list of files and line number where it made the update.
The solution can be in Perl/PHP/BATCH or anything thats nice and elegant
The code below uses Perl’s in-place editing feature to modify only those files that need changing and leaves backups of the originals. For example, if it updates
foo.php, the original will be infoo.php.bak.We begin with typical front matter. We’ll use the File::Find module to search for HTML and PHP files at any depth, starting by default in the current directory or in all directories named on the command line.
In
read_filelist, we get the list of transformations use them to generate two bits of code:Note the use of
\bwhich matches only at word boundaries andquotemeta, which escapes any regex metacharacters. These constrain the replacements to only literal occurrences of the old filenames.It’s a bit lengthy, so pardon the scrollbar.
Here we remember the root directories to begin searching and read
filelist.txt. Perl’s in-place editing requires the files to be updated to be in the special@ARGVarray.The sub
needs_updateis the worker thatFile::Find::finduses to check whether a given file should be modified. We could place all PHP and HTML files in@ARGV, but in cases when the code modifies nothing, you’d still get backup files for everything.For the main event, we clear
@ARGV, useneeds_updateto add the appropriate PHP and HTML files, and unleash the compiled sub on them.A couple of notes:
filelist.txt.<link>and<script>elements. Doing this correctly requires an HTML parser. If names of Javascript sources infilelist.txtshould not be replaced sometimes, I can update this answer with the extra machinery, but doing would add even more code.On Windows, paste the code (minus my running commentary) into a file with an extension of
.pl, and then run it asto patch HTML and PHP files beneath the current directory. To process one or more directories elsewhere, run