You are here:  » Image Caching with resize and proxy only mode


Image Caching with resize and proxy only mode

Submitted by support on Sun, 2015-10-04 12:16 in

Hi everyone,

I've collated the most frequent requests (resizing and more recently proxy only mode) into a single new version that combines these features as required. With merchant image sizes and aspect ratios varying widely, this new version supports tidy resizing to a fixed perfectly square image padded either top and bottom or left and right depending on the dimensions of the original image. For search results with considerable variation in merchant image dimensions this can improve the aesthetics of the search results considerably. To enable resizing, change the $imageCacheResize variable from FALSE to an integer value of the size required, e.g:

  $imageCacheResize = 250;

Proxy mode is something that has come about more recently with the move towards the secure web and search engines encouraging the use of https as standard. Most web browsers will display an exclamation mark icon in the address bar if an https page includes non-https resources - not a good look - so this feature enables you to use the script (with optional resizing) whilst only taking the bandwidth hit for image delivery rather than bandwidth + storage requirements. To use the script in proxy only mode, simply change the value of $imageCacheTime to 0:

  $imageCacheTime = 0;

This version also makes use of the $config_automationHandler variable, to support source image fetching using either PHP internal URL wrappers or CURL.

imageCache.php

<?php
  
require("includes/common.php");
  
$imageCacheDir "cache/"// set to writable folder for image cache storage
  
$imageCacheTime 604800;  // cache period in seconds, set to zero for proxy only mode
  
$imageCacheResize FALSE// set to resize dimension to enable  e.g. $imageCacheResize = 250;
  
function cacheFetch_auto($src)
  {
    if (
function_exists("curl_init"))
    {
      return 
cacheFetch_curl($src);
    }
    else
    {
      return 
cacheFetch_php($src);
    }
  }
  function 
cacheFetch_curl($src)
  {
    
$ch curl_init($src);
    
curl_setopt($ch,CURLOPT_HEADER,0);
    
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
    
curl_setopt($chCURLOPT_RETURNTRANSFER1);
    
$img curl_exec($ch);
    return 
$img;
  }
  function 
cacheFetch_php($src)
  {
    return 
file_get_contents($src);
  }
  function 
cacheFetch($src)
  {
    global 
$config_automationHandler;
    global 
$imageCacheDir;
    global 
$imageCacheTime;
    global 
$imageCacheResize;
    
$filename $imageCacheDir.md5($src);
    
$fetch = (
      (!
$imageCacheTime)
      ||
      (!
file_exists($filename))
      ||
      (
filemtime($filename) < (time()-$imageCacheTime))
      );
    if (
$fetch)
    {
      
$cacheFetch_fn "cacheFetch_".$config_automationHandler;
      
$img $cacheFetch_fn($src);
    }
    else
    {
      
$img file_get_contents($filename);
    }
    if (!
$res = @imagecreatefromstring($img)) return FALSE;
    if (
$imageCacheResize)
    {
      
$oldX imagesx($res);
      
$oldY imagesy($res);
      
$new imagecreatetruecolor($imageCacheResize,$imageCacheResize);
      
$newBackground imagecolorallocate($new,255,255,255);
      
imagefill($new,1,1,$newBackground);
      if (
$oldX $oldY)
      {
        
$newX $imageCacheResize;
        
$xMultiplier = ($newX $oldX);
        
$newY intval($oldY $xMultiplier);
        
$dstX 0;
        
$dstY = ($imageCacheResize 2) - ($newY 2);
      }
      else
      {
        
$newY $imageCacheResize;
        
$yMultiplier = ($newY $oldY);
        
$newX intval($oldX $yMultiplier);
        
$dstX = ($imageCacheResize/2)-($newX/2);
        
$dstY 0;
      }
      
imagecopyresized($new,$res,$dstX,$dstY,0,0,$newX,$newY,$oldX,$oldY);
      
ob_start();
      
imagepng($new);
      
$img ob_get_contents();
      
ob_end_clean();
    }
    if (
$fetch && $imageCacheTime)
    {
      
$fp fopen($filename,"w");
      
fwrite($fp,$img);
      
fclose($fp);
    }
    return 
$img;
  }
  
$src base64_decode($_GET["src"]);
  if (!
$img cacheFetch($src))
  {
    
header("HTTP/1.0 404 Not Found");
    exit();
  }
  else
  {
    
header("Content-Type: image");
    print 
$img;
    exit();
  }
?>

To implement image caching for Featured Products; look for the following code for the src attribute of the img tag at line 17 of html/featured.php:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

For Search Results, look for the following code for the src attribute of the img tag at line 19 of html/searchresults.php:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

And for the main product image, look for the following code for the src attribute of the img tag at line 46 of html/product.php:

src='<?php print htmlspecialchars($product_main["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product_main["image_url"]); ?>'

Proxy only mode only for non-https URLs

To implement proxy only mode and only for non-https image URLs on an https installation, a PHP ternary (short-hand if/then/else) can be used to render either the https or imageCache URL as required, for example for Featured Products, look for the following code for the src attribute of the img tag at line 17 of html/featured.php:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print (strpos($product["image_url"],"https")===FALSE?
           $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]):
           htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset)); ?>'

Cheers!
David
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-10-07 11:31

Hello David

Can we add image extension for cathced image
So I can add cache validator

Submitted by support on Wed, 2015-10-07 12:10

Hi,

Sure - only the one change required to include an extension in the cached filename, where you have the following code at line 36:

  $filename = $imageCacheDir.md5($src);

...REPLACE with:

  $filename = $imageCacheDir.md5($src).".png";

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-10-07 13:03

Hi David,

Thanks - works well.

Submitted by keshavkshirsagar on Mon, 2015-10-12 08:48

Hello David

If image not found how to set default no_image

Submitted by support on Mon, 2015-10-12 09:42

Hi,

If you upload your default fall-back image as

images/no-image.png

Then where you have the following code at line 53:

  if (!$res = imagecreatefromstring($img)) return FALSE;

...REPLACE with:

  if (!$res = imagecreatefromstring($img))
  {
    return file_get_contents("images/no-image.png");
  }

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Mon, 2015-10-12 12:24

Thanks for your quick support

Submitted by wesse249 on Mon, 2015-10-12 18:48

Hello,

I placed imageCache.php in the root and made the changes in featured, searchresults and products. But when i upload it al the images are gone.

Greetings Jan Roel

Submitted by support on Tue, 2015-10-13 08:06

Hello Jan,

It may be that the cache/ folder is not writable by PHP. The easiest way to do this is normally using your FTP program. In the remote window, right-click on the cache/ folder and look for Permissions... or maybe Properties... and then Permissions. Then give WRITE access to all users (Owner / Group / World) and that should be all it is...

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Thu, 2015-10-15 07:49

Hello David,

I work a lot with subdomains. http://www.pricetapestry.com/node/5653

But the images aren't cached in the subdain cache folder. Do i have to change this line?

require("includes/common.php");

Because this is my common.php:

{code saved}

Submitted by support on Thu, 2015-10-15 08:13

Hello Jan,

The cache/ folder is relative to the script as executed so they should be saving in the individual cache/ folder of each sub-domain. Is caching working, but images are all being saved in a single folder due to the setup?

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Thu, 2015-10-15 20:37

How can i check if it works? My cache folder is empty. I made him writeable to 777.

Further is made al changes to featured, searchresults and product in HTML

Submitted by support on Fri, 2015-10-16 08:28

Hello Jan,

Having made the changes, are images displaying correctly on your site?

What value are you using for $imageCacheTime? If that was set to zero for proxy only mode then no files would appear in the cache/ folder. if you'd like me to take a look at your site let me know an installation URL where imageCache.php is in use (I'll remove before publishing your reply) and I'll check it out for you...

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-11-04 07:51

Hi David,

1. How We Can stop image Cache if image already Cached previously ?

2. And Can We set name of Cached img with product name with its id ?

Submitted by support on Wed, 2015-11-04 08:54

Hi,

To prevent fetching of images cached previously is essentially caching for an unlimited period, so the fetching logic can simply be reduced to just whether or not the file exists; so where you have this code beginning at line 37:

    $fetch = (
      (!$imageCacheTime)
      ||
      (!file_exists($filename))
      ||
      (filemtime($filename) < (time()-$imageCacheTime))
      );

...REPLACE with just:

    $fetch = (
      (!file_exists($filename))
      );

If you would prefer to pass the product name through rather than image URL (perhaps for SEO purposes) then using name as the parameter in place of src, within your html/ files where you have added calls to imageCache.php e.g.

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

...use:

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product["normalised_name"]); ?>'

...or for the main product image in html/product.php:

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product_main["normalised_name"]); ?>'

And then in imageCache.php at line 91:

  $src = base64_decode($_GET["src"]);

...REPLACE with:

  $src = "";
  $name = tapestry_normalise($_GET["name"]);
  $sql = "SELECT image_url FROM `".$config_databaseTablePrefix."products` WHERE normalised_name = '".database_safe($name)."' AND image_url <> '' ORDER BY price ASC";
  if (database_querySelect($sql,$rows))
  {
    $src = $rows[0]["image_url"];
  }

Ordering by price will ensure that the same image is used in all instances...

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-11-04 11:17

Thanks David

Submitted by wesse249 on Thu, 2015-12-10 10:20

Hello David,

Images aren't showed. Map Cache is writeable 777. It also contains files.

But image aren't showed up. {link saved}

Do you have an answer?

Thanks Jan Roel

Submitted by support on Thu, 2015-12-10 11:11

Hello Jan,

I looks like your imageCache.php script has content outside of the <?php and ?> tags - possibly UTF-8 "Byte Order Markers". Open the file in your text editor, and first make sure that there are no new-lines or white space outside of the PHP code. Next, use your editor's File > Save As... menu and on the dialog look for a Character Encoding drop-down and see if you have a "UTF-8 NO BOM" option. Alternatively, "Include Byte Order Markers" may be an option in your editor's configuration, and if set disable the setting, save and re-upload the file and that should be all it is.

If still no joy, if you could email me your imageCache.php I'll check it out further for you...

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Thu, 2015-12-10 11:14

Thank you very much. That was the problem.

Submitted by philstone on Thu, 2015-12-10 14:56

Hi David

I was wondering is there a way to stop .png or .gif (transparent product images) coming up with a black background? using imagecache.php?

Thanks

Phil

Submitted by support on Thu, 2015-12-10 15:17

Hi Phil,

I assume that's a function of using resize, so where you have the following line:

      $newBackground = imagecolorallocate($new,255,255,255);

...REPLACE with:

      $newBackground = imagecolorallocatealpha($new,255,255,255,127);

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by philstone on Thu, 2015-12-10 15:49

Thanks David

I will try this!!

P

Submitted by dflsports on Wed, 2015-12-30 04:58

Hello. The image caching works fine until I try to implement the "If you would prefer to pass the product name through rather than image URL (perhaps for SEO purposes) then using name as the parameter in place of src, within your html/ files where you have added calls to imageCache.php "

I added the code the following to product.php

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product["normalised_name"]); ?>'

and to imageCache
$src = "";
  $name = tapestry_normalise($_GET["name"]);
  $sql = "SELECT image_url FROM `".$config_databaseTablePrefix."products` WHERE normalised_name = '".database_safe($name)."' AND image_url <> '' ORDER BY price ASC";
  if (database_querySelect($sql,$rows))
  {
    $src = $rows[0]["image_url"];
  }

Image links broken "<img alt="Image of Nebo Slyde" src="/imageCache.php?name=" data-pin-nopin="true">'

I see the following in the errlog

[30-Dec-2015 04:16:55 UTC] PHP Warning: imagecreatefromstring(): Empty string or invalid image in /home/XXX/public_html/imageCache.php on line 53
[30-Dec-2015 04:16:55 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /home/XXX/public_html/imageCache.php:53) in /home/XXX/public_html/imageCache.php on line 100

Any assistance is appreciated.

Submitted by support on Wed, 2015-12-30 09:09

Hi dflsports,

My apologies - for the product page (html/product.php) the $product_main variable should be used instead of $product - have a go with:

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product_main["normalised_name"]); ?>'

Now updated in the original post also...

Cheers,
David.
--
PriceTapestry.com

Submitted by stevebi on Wed, 2015-12-30 09:15

Hello David,

May I ask if I can apply image caching at my distribution and if I will need more disc space?

It will definitely help a lot

Great work

Cheers

Steve

Submitted by support on Wed, 2015-12-30 09:24

Hi Steve,

Assuming an average image size of say, 25K (25000 bytes) the disk space required would be approximately this times by the number of products on your site, so for an installation of 100,000 products this would be about 2.5GB. You can check the disk space available on your server using the disk free (df) command:

df -h

The -h flag displays the volume information in human readable format e.g. MB / GB rather than blocks...

Cheers,
David.
--
PriceTapestry.com

Submitted by stevebi on Wed, 2015-12-30 11:15

Thank you very much David,

And since I have several sites sharing the same database can I create an image folder from which all the websites will retrieve cached images?

Cheers

Steve

Submitted by support on Wed, 2015-12-30 12:00

Hello Steve,

Sure - the simplest approach would simply be to have your sub-domain installation image URLs point to the imageCache.php of the www. installation, so in the modifications to the html/ files to use imageCache.php in place of:

$config_baseHREF

...you would use:

"http://www.example.com/"

If you wanted to avoid linking between installations in that way an alternative option would be to create a new sub-domain on which to host imageCache.php, for example:

http://images.example.com/

You would not need to put a Price Tapestry installation in this sub-domain host, simply create the cache/ folder as usual, make sure it is writeable, and then upload imageCache.php modified as follows - where you have the following code at line 2:

  require("includes/common.php");

...REPLACE with:

  $config_automationHandler = "auto";

(to get the value of that variable is the only reason the require() is included)

Then, just as above to use the images. subdomain, in your modifications to the html/ files in place of:

$config_baseHREF

...you would use:

"http://images.example.com/"

(note the quotation marks in the above - these are required as you are replacing a variable with a string...)

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by stevebi on Wed, 2015-12-30 22:08

Hello David,

May I ask if and how I could apply a subdomain folder for merchant logos?

Because currently for every feed that I am adding I have to upload 4 times the same logo which means 4 folders with same images

Cheers

Steve

Submitted by dflsports on Thu, 2015-12-31 01:47

Thanks David! New code works like a charm!

Regards,

Don

Submitted by support on Thu, 2015-12-31 09:13

Hi Steve,

Sure - if you've made the images. subdomain for cached images as described above you can make a logos/ folder within that host and serve merchant logos for all your sites from the one location.

I know that your hosting set-up maps sub-directories to sub-domains and I've just realised that the suggestion of an images. sub-domain would conflict with the images/ sub-directory of a Price Tapestry installation so an alternative might be media e.g.

http://media.example.com/

- for imageCache.php and cache/ folder, and

http://media.example.com/logos/

With this set-up, the physical location of logo files within your hosting account would be

/home/example/public_html/media/logos/

To apply the changes within the files, first edit includes/tapestry.php and look for the following code at line 490:

  if (file_exists((is_dir("logos")?"logos/":"../logos/").$filename))

...and REPLACE with:

  if (file_exists("/home/example/public_html/media/logos/".$filename))

And then in html/prices.php look for the src attribute of the logo img tag at line 49:

  src='<?php print $config_baseHREF."logos/".$logoFilename?>'

...and REPLACE with:

  src='http://media.example.com/logos/<?php print $logoFilename?>'

And in merchants.php look for the following code at line 15:

  $item["logo"] = $config_baseHREF."logos/".$logoFilename;

...and REPLACE with:

  $item["logo"] = "http://media.example.com/logos/".$logoFilename;

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Sat, 2016-01-09 20:27

Hello David,

When i add the cache src to my file searchresults.php the page is never stopping loading? When i replace

<?php
 
print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); 
?>
' /> with orginal one then it stops.

Do you know how this is possible?

This is the code of my page:

{code saved}

Submitted by support on Mon, 2016-01-11 09:14

Hello Jan,

The page appearing to load continuously would indicate at least one of the imageCache.php image requests taking a long time to load. I have come across instances where, and i'm not yet entirely sure why, passing of the image URL using base64 encoding is resulting in corruption of the URL, so the first thing I would suggest is to pass using standard URL encoding instead.

To try this, in your imageCache.php file, replace base64_decode with urldecode and in your replacement to the html/ files, replace base64_encode with urlencode and that might do the trick. I am currently investigating this further, together with issues regarding extended utf-8 characters (e.g. accented vowels) that appear to be related...

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Mon, 2016-03-21 06:30

Hello David

Cached Images load quickly, But when images will cached newly it will take time to load on browser
because it will store first in cache folder then it will load

Now My question is How we can add image Lazy Load concept for this situation ?

Submitted by support on Mon, 2016-03-21 09:52

Hi,

It looks like there are a few Lazy Load jQuery extensions, for example this one but there are a number of them available. They work by having the image URL in a data attribute rather than the src attribute of an img tag, and then the lazyload function attached to such images via JavaScript / jQuery at the end of the page.

Firstly make sure that your chosen script is loaded in the header. Add the necessary code to html/header.php e.g.

  <script src='<?php print $config_baseHREF?>html/vendor/jquery.lazyload.js'></script>

And then to modify search results image tags, edit html/searchresults.php and locate the src attribute of the img tag around line 18:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and replace with:

class='lazy' data-original='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

And then finally in html/footer.php

<script type='text/JavaScript'>
$(function() {
    $("img.lazy").lazyload();
});
</script>

Hope this points you in the right direction!

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Mon, 2016-03-28 11:08

Thanks David

Submitted by keshavkshirsagar on Tue, 2016-08-09 17:47

Hello David

Can we store original size image in Cache folder
What will be value for $imageCacheResize to store original image?

Submitted by support on Wed, 2016-08-10 08:24

Hi,

Use;

  $imageCacheResize = FALSE;

...to disable resizing.

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Sat, 2016-08-13 11:38

Thanks David

Submitted by sirmanu on Thu, 2016-09-22 23:02

Sometimes, I get this warning:

"PHP Warning: imagecreatefromstring(): Data is not in a recognized format in /imageCache.php on line 54"

Line 54 is
if (!$res = imagecreatefromstring($img)) return FALSE;

http://php.net/manual/en/function.imagecreatefromstring.php

As I see is because sometimes the images are down (404 not found). Is it possible that in order to avoid this error, set up a generic image from my images folder?

Submitted by support on Fri, 2016-09-23 08:39

Hi,

Sure - upload your generic "no image" image as, for example images/generic.jpg and then in place of the following code that issues the 404;

    header("HTTP/1.0 404 Not Found");
    exit();

...have a go with:

    $img = file_get_contents("images/generic.jpg");
    header("Content-Type: image");
    print $img;
    exit();

Cheers,
David.
--
PriceTapestry.com

Submitted by sirmanu on Fri, 2016-09-23 09:08

But modifying that, I will still having that warning, isn't it?
By the way, images with spaces, are not displayed.
I think it might be of your interest add this piece of code

str_replace(" ","%20",$image)

Submitted by support on Fri, 2016-09-23 09:18

Hi,

Sorry I missed that part - the warning can be suppressed with the @ prefix, so where you have:

    if (!$res = imagecreatefromstring($img)) return FALSE;

...REPLACE with:

    if (!$res = @imagecreatefromstring($img)) return FALSE;

I will look into the %20 encoding further, Image URLs should be correctly formatted from source, consider that there is no processing of the URLs before rendering directly into a page.

Cheers,
David.
--
PriceTapestry.com

Submitted by Keeop on Mon, 2016-10-03 21:39

Hi David,

Getting grief from a particular merchant for hammering their servers with image requests. From what I can tell, it's bots and spiders crawling my site pinging off the GET requests at a rapid rate. Is there any way alter the image cache script to detect spiders/bots etc. and stop them from firing off these requests?

Cheers.
Keeop

Submitted by support on Tue, 2016-10-04 08:10

Hi Keeop,

This is one of the downsides of caching of course - one may come across merchant's who's servers are configured to detect repeated requests from a single IP and may even block under some conditions.

You could try adding a check for an HTTP_REFERER - bots often don't include the referer - to try this, where you have the following code:

  $src = base64_decode($_GET["src"]);

...REPLACE with:

  if (!isset($_SERVER["HTTP_REFERER"]) || !$_SERVER["HTTP_REFERER"]) exit();
  $src = base64_decode($_GET["src"]);

Also, if not already in place, it might be worth adding a crawl-delay to robots.txt:

User-agent: *
Crawl-delay: 2

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Keeop on Thu, 2016-10-06 13:39

Thanks David, I'll give those a go. And yes, my IP is currently banned by that merchant because of it!

Cheers.
Keeop

Submitted by Retro135 on Tue, 2016-11-15 06:33

Is there any way to add width/height to the cached image URLs?

Submitted by support on Tue, 2016-11-15 09:21

Hi,

It would be no problem to pass the resize width in as a parameter in the URL, allowing for differently resized images for use in different scenarios (e.g. Featured Products / main product image). Note that this will result in potentially doubling the number of files held in the cache folder so consider this in terms of bandwidth / disk space impact.

To do this, where you have the following code at line 5:

  $imageCacheResize = FALSE;

...REPLACE with:

  $imageCacheResizeMax = 1024; // set to the maximum width you are likely to use
  $imageCacheResize = intval($_GET["w"]);
  if ($imageCacheResize > $imageCacheResizeMax) exit();

And then the following code at line 36:

    $filename = $imageCacheDir.md5($src);

...and REPLACE with:

    $filename = $imageCacheDir.md5($src)."_".$imageCacheResize;

And then to use, where you would now have for, say, Featured Products:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

...add the w parameter in the src URL for example:

src='<?php print $config_baseHREF."imageCache.php?w=100&src=".base64_encode($product["image_url"]); ?>'

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Retro135 on Tue, 2016-11-15 16:36

Never mind! " ...this will result in potentially doubling the number of files held in the cache folder so consider this in terms of bandwidth / disk space impact." Filing this under "Be careful what you ask for!" Thank you!

Submitted by Perce2 on Thu, 2016-12-15 10:28

Hi David,

In the middle of moving my sites over to https. So far appear to be having success using your methods in this post - "Proxy only mode only for non-https URLs"

However, I have now come to stand still whilst trying to accomplish this with my Wordpress installs!
Do we still need to use ImagheCache.php ? Where do we put it ? What code changes are needed ?

Thanks for any assistance you may offer.

Submitted by support on Thu, 2016-12-15 10:46

Hi,

Firstly, edit the plugin file pto_search.php and look for the following code at line 518:

      $each = str_replace("%IMAGE_URL%",$row->image_url,$each);

...and REPLACE with:

      $each = str_replace("%IMAGE_URL%",$row->image_url,$each);
      $each = str_replace("%IMAGE_URL64%",base64_encode($row->image_url),$each);

And then edit pto_product.php and look for the following code at line 392:

      $html_product = str_replace("%IMAGE_URL%",$product->image_url,$html_product);

...and REPLACE with:

      $html_product = str_replace("%IMAGE_URL%",$product->image_url,$html_product);
      $html_product = str_replace("%IMAGE_URL64%",base64_encode($product->image_url),$html_product);

With that in place, you can then edit your Search Results / Each and Product / Main templates, and where you would currently use the %IMAGE_URL% placeholder in the src attribute of the img tag e.g.

src='%IMAGE_URL%'

...instead, create an absolute link to your imageCache.php using the new %IMAGE_URL64% placeholder added by the above modifications e.g.

src='/pt/imageCache.php?src=%IMAGE_URL64%'

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 13:58

Hi David,

thanks for the quick explanation.

I managed to keep up with you until "With that in place..."

Don't I need to edit the main templates: searchresults.php / featured.php / product.php as I did with the non-wordpress pt version ?

If so, not sure which part to edit, as I have in place now:

{code saved}

Where do I add:

src='/pt/imageCache.php?src=%IMAGE_URL64%'

Sorry for any confusion!

Thanks.

Submitted by support on Thu, 2016-12-15 15:13

Hi,

When using the plugin, the Price Tapestry installation's /html/ folder files aren't used at all - the content generated within your WordPress site is based on the templates which you can edit from /wp-admin/ > Settings > PriceTapestry.org. On that page, scroll down to the Templates section where you will find Search Results / Each and Product / Main templates which is where the changes need to be made...

Cheers,
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 16:20

Made the changes as instructed, now have no images on "product" and "search-results" pages!
Also, as I have a customised "pto_featured.php" I think this is effecting any changes on the main index page as the results still look the same.

Thanks David.

Submitted by support on Thu, 2016-12-15 17:31

Hi,

Ah - I forgot the same change required in pto_featured.php - line 81:

          $each = str_replace("%IMAGE_URL%",$row->image_url,$each);

...REPLACE with:

          $each = str_replace("%IMAGE_URL%",$row->image_url,$each);
          $each = str_replace("%IMAGE_URL64%",base64_encode($row->image_url),$each);

And similarly, in /wp-admin/ > Settings > PriceTapestry.org, for the Featured Products / Each template you would need to change

src='%IMAGE_URL%'

...to:

src='/pt/imageCache.php?src=%IMAGE_URL64%'

Note that in the above template modification, and the previously described changes to Search Results / Each and Product / Main, the /pt/ part is the path to the associated Price Tapestry Installation, so if not installed in /pt/ this would need to be changed, e.g. if installed in /comparison/ then the replacements would be;

src='/comparison/imageCache.php?src=%IMAGE_URL64%'

(the part in front of imageCache.php should be the same as $config_baseHREF setting in config.php of the associated Price Tapestry installation...)

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 18:12

Implemented all the changes as suggested but still getting all images missing!

Typical missing image link showing like:
{code saved}

What do you think ?

Submitted by support on Thu, 2016-12-15 18:19

Hi,

It looks like it's missing both the enclosing ' and the path to imageCache.php - could you perhaps copy / paste into a reply your content for the following templates:

Featured Products / Each

Search Results / Each

Product / Main

Thanks!
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 18:33

FEATURED

%IF_IMAGE%
  <p><a href='%PRODUCT_URL%'><img src='/pt/imageCache.php?src=%IMAGE_URL64%' /></a></p>
%ENDIF_IMAGE%

SEARCH

%IF_IMAGE%
  <a href='%PRODUCT_URL%'><img class='pto_search_image' src='/pt/imageCache.php?src=%IMAGE_URL64%' /></a>
%ENDIF_IMAGE%

PRODUCT

%IF_IMAGE%
<div class='pto_col-s-10 pto_col-m-5 pto_pr-img'>
<img src='/pt/imageCache.php?src=%IMAGE_URL64%' />
</div>
%ENDIF_IMAGE%

Submitted by support on Fri, 2016-12-16 09:30

Hi,

That looks perfect, but for some reason it's not correlating with the output being generated that you posted previously....

Please could you check a product page again, and copy the HTML section that corresponds with the above IMAGE section of the Product / Main template - if you search in the View > Source for "pto_pr-img", then copy / paste the div / img tags....

Altermatively, if you'd like to email me a link to your installation, (example product page URL) and attach modified pto_product.php I'll follow up by email with you...

Thanks,
David.
--
PriceTapestry.com

Submitted by sirmanu on Tue, 2017-07-18 07:30

Hi David. As I noticed earlier, images with spaces was not displayed.

Example:

"https://www.example.com/images/products/BROOKS ADURO 4 BLACK RED.jpg" (working)

However, when using imagecache is not displayed.

I added these two lines an now is working:

  $src = base64_decode($_GET["src"]);
  $src = trim($src);
  $src = str_replace ( ' ', '%20', $src);

Regards and hope is useful for someone with my same problem

Submitted by nVIsion on Mon, 2017-07-31 15:04

This image cache code works great but I am wondering if it is possible to maintain the aspect ration of the image. Many of the images I am working with are different sizes and right now when I set the resize to 300 it creates a white background on the top/bottom or the sides of the images. Is there any way to restrict the width to 300 yet still keep the aspect ratio of the photo and having no new background? Thanks!

Submitted by support on Tue, 2017-08-01 16:40

Hello nVision and welcome to the forum!

The resized images should maintain the original image's aspect ratio however that will result in the white border above / below or left / right (depending on original image aspect ratio) as you are seeing however you could experiment with a transparent background instead. To try this, edit imageCache.php and where you should have the following code beginning at line 59:

      $newBackground = imagecolorallocate($new,255,255,255);

...REPLACE with:

      $newBackground = imagecolorallocatealpha($new,0,0,0,127);
      imagefill($new,1,1,$newBackground);
      imagesavealpha($new,TRUE);

Don't forget to empty the cache/ folder after uploading so that the cached files are created with the modifications in place...

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by marco on Mon, 2018-02-12 13:11

Hello,

I am, layout wise, also looking for a different image than the square one.
Would it be possible to crop the image to a fixed aspect ratio of 3:2?

Best,
Marco

Submitted by support on Mon, 2018-02-12 15:00

Hello Marco,

Make sure you're using resize and a value for $imageCacheResize that is exactly divisible by 3 for example imageCache.php at line 5:

  $imageCacheResize = 240;

And then look for the following code at line 77:

      imagecopyresized($new,$res,$dstX,$dstY,0,0,$newX,$newY,$oldX,$oldY);

...and REPLACE with:

      imagecopyresized($new,$res,$dstX,$dstY,0,0,$newX,$newY,$oldX,$oldY);
      $cropHeight = intval(($imageCacheResize / 3) * 2);
      $cropY = intval(($imageCacheResize - $cropHeight) / 2);
      $new = imagecrop($new,array("x"=>0,"y"=>$cropY,"width"=>$imageCacheResize,"height"=>$cropHeight));

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by TWDesigns on Sat, 2018-03-10 17:52

Is this still true to newest version? I followed the instructions at the time and it started caching the images into the folder but it wouldn't display the images. Instead of just said img src="imageCache.php or src="".

Thanks!

Submitted by support on Mon, 2018-03-12 11:43

Hi,

Everything in the main post is current for 16/10A - if still no joy if you include in your email (re removing .html) any modified html/ files to use imageCache.php I'll double check those for you...

Cheers,
David.
--
PriceTapestry.com

Submitted by philstone on Tue, 2018-04-03 22:08

Hi David

I keep getting error:

imagejpeg() expects parameter 1 to be resource, string given in /home/*******/public_html/imageCache.php on line 80

Could you please advise what I should do to fix this

{code saved}

Many thanks

Phil

Submitted by support on Wed, 2018-04-04 11:50

Hi Phil,

Where you have the following code beginning at line 80:

  imagejpeg($img, NULL, 90);
  imagejpeg($new);

...it looks like that should be just:

  imagejpeg($new, NULL, 90);

Cheers,
David.
--
PriceTapestry.com

Submitted by philstone on Wed, 2018-04-04 20:45

Thanks so much David!!

Submitted by sirmanu on Mon, 2018-07-09 10:05

Hi David.
I have been banned in some merchants.
Is it possible to disable in some of them?

Submitted by support on Thu, 2018-07-12 14:32

Hi,

One thing you could do if certain hosts have blocked your server from making the image requests is to make a new function to return the image URL, either the cached URL, or the URL itself if the host is in an array of merchant image servers that should not be cached.

To do this, add the following new function to includes/tapestry.php:

  function tapestry_imageURL($image_url)
  {
    global $config_baseHREF;
    $noCache = array("www.example.com","www.example.org");
    $host = parse_url($image_url,PHP_URL_HOST);
    if (in_array($host,$noCache))
    {
      return $image_url;
    }
    else
    {
      return $config_baseHREF."imageCache.php?src=".base64_encode($image_url);
    }
  }

Edit the $noCache array to contain the list of hosts not to cache; and then in the html/ files, for example in html/product.php (original) in place of:

src='<?php print htmlspecialchars($product_main["image_url"],ENT_QUOTES,$config_charset); ?>'

...use

src='<?php print htmlspecialchars(tapestry_imageURL($product_main["image_url"]),ENT_QUOTES,$config_charset); ?>'

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by bigshopper on Thu, 2018-10-11 14:48

Hi David,

I changed a lot and now my product.php looks like:

    <div class='small-8 medium-4 columns'><img alt='<?php print translate("Image of"); ?> <?php print htmlspecialchars($product_main["name"],ENT_QUOTES,$config_charset); ?>' src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product_main["normalised_name"]); ?>' /></div>

The image URL is:
https://example.com/imageCache.php?name=5Aaa-CarParts-Gr%C3%BCn-102x132cm

How to change this URL to:
https://example.com/cache/5aaa-carparts-grun-102x132cm.png

So: the filetype is added, the URL is in lowercase and strange characters are replaced by "normal" (nonAscii) characters.

Submitted by support on Fri, 2018-10-12 07:51

Hi,

All you need to do is add a suitable rule to .htaccess - have a go with the following - add to the end of .htaccess:

RewriteRule ^cache/(.*).png$ imageCache.php?name=$1 [B,L]

And then your html/product.php modification can be as follows;

    <div class='small-8 medium-4 columns'><img alt='<?php print translate("Image of"); ?> <?php print htmlspecialchars($product_main["name"],ENT_QUOTES,$config_charset); ?>' src='<?php print $config_baseHREF."cache/".tapestry_hyphenate($product_main["normalised_name"]); ?>.png' /></div>

Cheers,
David.
--
PriceTapestry.com

Submitted by bigshopper on Wed, 2018-10-17 06:44

Hi David,

Thanks! It works now, I have only one problem at the homepage and another question. At the homepage I get now an error:

{code saved}

And this solution, till how many products will this work? If we have 2 million products, won't this cause problems to have 2 million images in one folder?

Robert

Submitted by bigshopper on Wed, 2018-10-17 07:17

Another question, it seems with your last reaction the image is not saved in the cache folder, but does work with the rewrite URL, absolutely perfect. But, there are a few things I wonder if that could be changed:
- The image URL's in lower case.
- Now all URL's do work (status 200 OK and and image, if not available, the "not available" image shows). This creates an enormous amount of URL's for Google. How to get this right: if an image URL doesn't work, it should result in an 404 page, but within the website: no image should show the "no image" image.

I hope you can help, thanks for all the support.

Robert

Submitted by support on Wed, 2018-10-17 10:11

Hi Robert,

It sounds like you have made a modification to return your "no image" image in the case of a 404 however if you re-instate that code so that imageCache.php can return 404 you can use the onError attribute of the img tag to change the src to the "no image" image. So to apply this, and also to make the rewritten URL lower case, based on your code posted above have a go with;

    <div class='small-8 medium-4 columns'><img alt='<?php print translate("Image of"); ?> <?php print htmlspecialchars($product_main["name"],ENT_QUOTES,$config_charset); ?>' src='<?php print $config_baseHREF."cache/".tapestry_hyphenate(strtolower($product_main["normalised_name"])); ?>.png' onError='JavaScript:this.src="/images/noimage.png";' /></div>

(change "/images/noimage.png" as required)

Cheers,
David.
--
PriceTapestry.com

Submitted by crounauer on Thu, 2018-11-29 08:18

Morning David,
I have installed the imacge cache script but can't get it to work and don't know where to start looking.

What I have done so far...

1. Checked that curl is installed {link saved}
2. Changed cache folder permission to 777

- Images are not being shown but the image url is being formed => {link saved}
- The cache folder is empty

These are the settings in imageCache.php

$imageCacheDir = "cache/"; // set to writable folder for image cache storage
$imageCacheTime = 604800; // cache period in seconds, set to zero for proxy only mode
$imageCacheResize = 250; // set to resize dimension to enable e.g. $imageCacheResize = 250;

It's a niche site setup with structure as follows: -

{link saved}

Thanks in advance.
Simon

Submitted by support on Thu, 2018-11-29 09:17

Hi Simon,

With a direct request to the cache image URL just returning a blank page it would indicate that a fatal error is occurring. To reveal the error, try adding the following code to the top of imageCache.php:

  ini_set('display_errors','on');error_reporting(E_ALL);

Then request the image URL that you copied into your post directly and you may see an error message displayed. If you're not sure from the output where the problem lies, or if not difference, let me know and I'll check it out further with you (I checked in your info.php that GD library is installed so shoudn't be that...)

Cheers,
David.
--
PriceTapestry.com

Submitted by crounauer on Thu, 2018-11-29 09:30

Hi David,

No error message showing on => {code saved}

It does say 404, which indicates that the page cannot be found.

Thanks,
Simon

Submitted by support on Thu, 2018-11-29 10:43

Hi Simon,

Ah - this could be the https SSL issue - if the server has been online for some time it may not have the latest authority certificates to verify https image URLs. To check for this, edit imageCache.php and where you have the following code at line 22:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

...and REPLACE with:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);

(if that does the trick don't forget to remove the error reporting code from the script...)

Cheers,
David.
--
PriceTapestry.com

Submitted by crounauer on Thu, 2018-11-29 11:01

Hi David,

I've not had any luck with the additional settings.
I have taken the "force https" redirect out of my .htaccess to see if it was the SSL causing the issue but it's still the same.

Thanks,
Simon

Submitted by support on Thu, 2018-11-29 11:11

Hi Simon,

I should have included this with the above mod sorry - another workaround for cases where the remote servers are configured to look for browser-looking user-agent is to set the user-agent to identify as a browser rather than CURL. To do this, add the following line at the same point as the SSL CURL options in the above mod;

    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by crounauer on Thu, 2018-11-29 11:16

Hi David,

FYI - As it's a niche site, I host all the images.

Thanks,
Simon

Submitted by support on Thu, 2018-11-29 11:20

Hi Simon,

Please could you email me the imageCache.php that you have so far and I'll check it out further with you...

Thanks,
David.
--
PriceTapestry.com

Submitted by sirmanu on Sun, 2019-11-03 15:27

Hi! It seems that imagecreatefromstring is not working with webp.

The error is "PHP Warning: imagecreatefromstring(): Data is not in a recognized format"

Any ideas?

Submitted by support on Mon, 2019-11-04 10:40

Hi,

It looks like WebP support is often not compiled into the GD library by default - you can double check the support formats with phpinfo() under the GD section.

A search for "php gd webp support" returns several pages that indicate what is required. I'll look into this further as WebP is widely supported now...

Cheers,
David.
--
PriceTapestry.com

Submitted by sirmanu on Tue, 2019-11-05 11:20

Weird, because with phpinfo() it says

WebP Support: enabled

GD Support enabled
GD headers Version 2.2.5
GD library Version 2.2.5
FreeType Support enabled
FreeType Linkage with freetype
FreeType Version 2.8.1
GIF Read Support enabled
GIF Create Support enabled
JPEG Support enabled
libJPEG Version 8
PNG Support enabled
libPNG Version 1.6.34
WBMP Support enabled
XPM Support enabled
libXpm Version 30411
XBM Support enabled
WebP Support enabled

Submitted by support on Tue, 2019-11-05 11:37

Hi,

That's strange - perhaps try a test script outside of imageCache.php - upload a test.webp valid image and then something like;

<?php
  ini_set
('display_errors','on');
  
error_reporting(E_ALL);
  
$webp file_get_contents("test.webp");
  
$image imagecreatefromstring($webp);
  print (
is_resource($image)?"OK":"ERROR");
?>

Cheers,
David.
--
PriceTapestry.com

Submitted by sirmanu on Tue, 2019-11-05 11:59

That code works
I am using this image {link saved}

It is weird.

If I var_dump what cacheFetch($src) returs, for a normal image is something like this:

string(5640) "JFIF>CREATOR: gd-jpeg v1.0 (using IJG JPEG v80)

However, when is Webp, is first say boolean(false) + the string

bool(false)
JFIF <CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 100

Submitted by sirmanu on Tue, 2019-11-05 12:07

Sorry, the previous message was wrong except from the URL of the image being tested. It was due a small modification.

Removing the @ from imagecreatefromstring throws the previous error: "PHP Warning: imagecreatefromstring(): Data is not in a recognized forma"

Submitted by support on Tue, 2019-11-05 12:10

Hi,

Is your imageCache.php working fine with other https URLs?

This is something that is copping up quite often now with servers that have been online for years not having the latest authority certificates (or even protocol support) for the latest https implementations...

Cheers,
David.
--
PriceTapestry.com

Submitted by sirmanu on Tue, 2019-11-05 12:12

Incredible!
It seems that the error comes from cacheFetch_curl and the user AGENT I am using in order to avoid to be banned.

$agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36';

curl_setopt($ch, CURLOPT_USERAGENT, $agent);

If I remove that line, it works...

Submitted by support on Tue, 2019-11-05 12:17

Strange! You normally have to add things like that to _make_ it work for some servers (that don't like curl/wget agents). If necessary you could do it conditionally e.g.

if (strpos($src,"example.com")===FALSE)
{
  curl_setopt($ch, CURLOPT_USERAGENT, $agent);
}

Cheers,
David.
--
PriceTapestry.com

Submitted by Antony on Thu, 2021-01-14 07:23

Hello David hope you are well,

I'm trying add the following: Cache-Control: max-age=31536000

From what I understand it may improve page loading speed.

I already have the following in html/header.php (at the very top) which seems to work great.

<?php header("Content-Type: text/html;charset=".$config_charset); $shoppingListCookie "shoppingList".bin2hex($config_baseHREF); $shoppingList = (isset($_COOKIE[$shoppingListCookie])?unserialize($_COOKIE[$shoppingListCookie]):array()); ob_start("ob_gzhandler"); ?>

Tried this but this doesn't seem to be correct for semi-obvious reasons to me where I think I need to merge the 2 headers:

<?php header("Content-Type: text/html;charset=".$config_charset); header("Cache-Control: max-age=31536000); $shoppingListCookie = "shoppingList".bin2hex($config_baseHREF); $shoppingList = (isset($_COOKIE[$shoppingListCookie])?unserialize($_COOKIE[$shoppingListCookie]):array()); ob_start("ob_gzhandler"); ?>

Can you suggest a solution?

Many thanks,

Ant

Submitted by support on Thu, 2021-01-14 08:28

Hello Ant,

There was a closing " missing in the new header() call, have a go with:

<?php header("Content-Type: text/html;charset=".$config_charset); header("Cache-Control: max-age=31536000"); $shoppingListCookie "shoppingList".bin2hex($config_baseHREF); $shoppingList = (isset($_COOKIE[$shoppingListCookie])?unserialize($_COOKIE[$shoppingListCookie]):array()); ob_start("ob_gzhandler"); ?>

That should be all it is...

Cheers,
David.
--
PriceTapestry.com

Submitted by Antony on Sun, 2021-01-17 08:35

Thank you David!

Submitted by Antony on Mon, 2021-01-18 16:20

Hi David,

Hope you are well,

I've noticed that the ShoppingList no longer works when I add the Cache-Control as bellow:

<?php header("Content-Type: text/html;charset=".$config_charset); header("Cache-Control: max-age=31536000"); $shoppingListCookie "shoppingList".bin2hex($config_baseHREF); $shoppingList = (isset($_COOKIE[$shoppingListCookie])?unserialize($_COOKIE[$shoppingListCookie]):array()); ob_start("ob_gzhandler"); ?>

Any thourghts?

Thanks,

Antony

Submitted by support on Tue, 2021-01-19 08:55

Hi Antony,

Ah - specifically allowing caching with cache-control means that when shoppinglist.php is requested it is not necessarily actually reloaded in order to reflected the just added or removed items.

What I would suggest then is not to use the header on shoppinglist.php, so instead of including the Cache-Control header within the above line, add a new line immediately afterwards as follows;

<?php if (strpos($_SERVER["SCRIPT_FILENAME"],"shoppinglist.php")===FALSEheader("Cache-Control: max-age=31536000"); ?>

(use CTRL+F5 to force a reload of shoppinglist.php for the first time after applying the change...)

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Antony on Tue, 2021-01-19 19:51

Hi David, If I understand correctly I should now have the following:

<?php header("Content-Type: text/html;charset=".$config_charset); $shoppingListCookie "shoppingList".bin2hex($config_baseHREF); $shoppingList = (isset($_COOKIE[$shoppingListCookie])?unserialize($_COOKIE[$shoppingListCookie]):array()); ob_start("ob_gzhandler"); ?>
<?php if (strpos($_SERVER["SCRIPT_FILENAME"],"shoppinglist.php")===FALSEheader("Cache-Control: max-age=31536000"); ?>

With this in place, the ShoppingList is now partially working. (note that I don't actually have a product page to action the shopping list - only through the search results)

So now when adding products to the cart I need to manually refresh the page to see quantities adding up within the cart (including ticking added products) despite product being added correctly and cart within functioning correctly. you can test what I mean here for example: {link saved}

I tried to replace shoppinglist.php with search.php where it all works great within the search results but of course no longer within the shoppinglist.

Sorry to bother you with this but this beats me...and the Cache-Control has significantly improved my Lighthouse Audit score and with my limited knowledge I feel that this may be a simple fix.

Many thanks in advance for your amazing support.

Antony

Submitted by support on Wed, 2021-01-20 09:17

Hi Antony,

To test for both search.php and shoppingList.php you can use:

<?php if ((strpos($_SERVER["SCRIPT_FILENAME"],"shoppinglist.php")===FALSE) && (strpos($_SERVER["SCRIPT_FILENAME"],"search.php")===FALSE)) header("Cache-Control: max-age=31536000"); ?>

Cheers,
David.
--
PriceTapestry.com

Submitted by Antony on Wed, 2021-01-20 15:36

You're a genius! ;)

Submitted by macland on Thu, 2021-01-28 15:16

Hi David

I just added the image cache script - it's so cool for speeding up sites, I should have done this a long time ago, thank you for adding this :-)

But now when I start to look at speed optimization there are two more things I come across:

1 - Google Pagespeed tells me that I should serve next-gen images. (https://web.dev/uses-webp-images/)
2 - GTmetrix tells tells me the same about next-gen images, but also that I should encode my images (https://gtmetrix.com/efficiently-encode-images.html)

I know I'm asking for perfect instead of just settling for my new, faster loading, but any idea how on how to not only cache and resize the image, but also compress it and serve it as a WebP file?

Submitted by support on Fri, 2021-01-29 08:04

Hi,

Thanks for noting this, WebP format was added to the GD library at PHP v5.4 so as long as you are running that or later (the majority of hosts are at PHP 7 now) then you should just be able to replace:

      imagepng($new);

with:

      imagewebp($new);

Don't forget to empty the cache folder after making any changes so that the images are re-created in the new format...

Cheers,
David.
--
PriceTapestry.com

Submitted by macland on Fri, 2021-01-29 10:02

Well that was incredibly easy to implement, thank you very much :-D