Hi
I'm trying to prevent caching by appending a '? t=' to the end of my JS files. What's the fastest way to get such a number? time() or rand() or something else?
Hi
I'm trying to prevent caching by appending a '? t=' to the end of my JS files. What's the fastest way to get such a number? time() or rand() or something else?
If you're only preventing caching, time() would be sufficient.
Don't use rand(), use mt_rand().
It uses a random number generator with known characteristics using the Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
time() and mt_rand() are pretty similar in terms of efficiency in PHP—you select one or the other based on what factors you need it for:
If you really want to know, time() is slightly faster—but you really don't need to worry about it. (It's the difference between one or two small parts of a second.)
(mt_rand() is about 4 times as fast as rand())
You probably know this already, but be sure to always profile your code before making optimizations; often it'll run slowly for reasons completely different than what you expected.
Call me old-fashioned, but preventing caching is something that can and should be achieved by using HTTP headers, not unique URLs. If you serve the file dynamically through PHP:
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>
otherwise use a .htaccess file in apache (or similar config in any other web server):
<FilesMatch "\.js$">
Header set Cache-Control "no-cache, must-revalidate"
Header set Expires "Sat, 26 Jul 1997 05:00:00 GMT"
</FilesMatch>