开发者

How To Append A Randomized or Date-Based Query String to Images

Internet Explorer has issues. In this case, caching issues. Images that have been saved to my server, an开发者_高级运维d are referenced in my dynamically generated site (WordPress) display as a "red x" in IE8 when those images are modified somehow, but the URI of the image isn't changed in the code, sometimes.

When I do change the URI of these resources, the images display properly in IE. I therefore want to append a somewhat unique query string to the end of my image URI's (a.k.a. change "graphic.png" to "graphic.png?d=a334bc4zxdg2" (if randomized) or "graphic.png?d=201103091616" (if dated). I am not picky about a randomized query string or "dated" query string - just as long as it's a nice long query string appended to the end of .PNG and .JPG filetypes.

I have attempted to write my own, and am thus extremely humbled. I figure this would be resolved with a preg_replace statement... something along the lines of

<php
echo preg_replace('(png|jpg)', '$1.?d.=<the-randomizing-or-timestamp-code>','some-subject-I-dont-know-how-to-specify')
?>

As you can tell from above, I need lots of help writing this code. Please note, I am operating in WordPress, which uses some unique hooks, and I'm trying to apply this to the full content of the body. Thanks SO!

== Update ==

A friend suggests the following:

// Append PNG files with timestamp query string
function date_images () {
    $new_content = str_replace (".png" ,".png?id=".time() ,$original_content);
    }

add_filter('the_content', 'date_images');

Is that on the right path? It doesn't work properly in Wordpress, but makes the content element entirely disappear. Thanks for your help...


You would be better off implementing this as a client side fix so that non-IE users could still get the regular image URLs.

I would try this:

<script type="text/javascript" src="PATH-TO-JQUERY"></script>
<script type="text/javascript">
// document.all is IE only
if ( document.all )
{
    $(document).ready(function(){
        // grab each image
        $('img').each(function(){
            var date = new Date;
            // add the current unix timestamp in microseconds to the the image src as a query string
            this.src = this.src + '?' + date.getTime();
        });
    });
}
</script>

<img src="image1.gif" />
<img src="image2.gif" />
<img src="image3.gif" />


If i understand you right, you could just do:

echo $variable.'?d='time();

To append a unixtime stamp to the end of the string.


All that needs to be done is to trick the browser into reloading the image.

The filename can stay the same everywhere, the only change needed is to the img src="" when you decide to display the image.

Something like this:

<img src="<?php echo $img_name.'?'.time(); ?>" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜