Image Cache using phpThumb and Mod_Rewrite

Generate thumbs by visiting a URL such as your.com/thumbs/50x50/images/image.jpg. This will create a 50x50px thumbnail of your.com/images/image.jpg.

The thumb will be stored on your server at your.com/thumbs/50x50/images/image.jpg so the next request for the same image will be loaded without loading php for ultra fast image cache.

Introduction

About a year ago I came across a fantastic script called phpThumb. It is an open source project used to resize images. Sure you can do the same thing with tools such as GD2 or imagemagick (or magickwand), however its much nicer to not have to worry about those things and just focus on getting the right image with ease.

It was as easy as

<img src="/phpthumb/phpThumb.php?src=myimage.jpg&w=100&h=100">

The problems started to arise on high-volume servers when apache had to get PHP to parse the phpThumb code for every image requested. Sure it has caching but it still has to load PHP to decide if it should use the cache or not.

In the past I have seen this issue solved using mod_rewrite to redirect non-existent images to a script where they can be generated. As a proof-of-concept I will provide the basic information required to get this running.

What you need

  • Apache
  • mod_rewrite
  • PHP

These things usually come with dedicated and shared hosting servers by default, however installation is beyond the scope of this article.

Ok, just tell me how to do it!

Upload phpThumb

Download phpThumb from here:
http://phpthumb.sourceforge.net/

Upload phpThumb to yoursite.com/phpthumb

Setup Mod_Rewrite

Create yoursite.com/thumbs/.htaccess

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?thumb=$1 [L,QSA]
</IfModule>

Create the Thumbnail Generator

Create yoursite.com/thumbs/index.php

/**
 * Create a thumbnail
 *
 * @author Brett @ Mr PHP
 */
 
// define allowed image sizes
$sizes = array(
	'157x153',
	'600x600',
);

// ensure there was a thumb in the URL
if (!$_GET['thumb']) {
	error('no thumb');
}

// get the thumbnail from the URL
$thumb = strip_tags(htmlspecialchars($_GET['thumb']));

// get the image and size
$thumb_array = explode('/',$thumb);
$size = array_shift($thumb_array);
$image = '../'.implode('/',$thumb_array);
list($width,$height) = explode('x',$size);

// ensure the size is valid
if (!in_array($size,$sizes)) {
	error('invalid size');
}

// ensure the image file exists
if (!file_exists($image)) {
	error('no source image');
}

// generate the thumbnail
require('../phpthumb/phpthumb.class.php');
$phpThumb = new phpThumb();
$phpThumb->setSourceFilename($image);
$phpThumb->setParameter('w',$width);
$phpThumb->setParameter('h',$height);
$phpThumb->setParameter('f',substr($thumb,-3,3)); // set the output format
//$phpThumb->setParameter('far','C'); // scale outside
//$phpThumb->setParameter('bg','FFFFFF'); // scale outside
if (!$phpThumb->GenerateThumbnail()) {
	error('cannot generate thumbnail');
}

// make the directory to put the image
if (!mkpath(dirname($thumb),true)) {
        error('cannot create directory');
}

// write the file
if (!$phpThumb->RenderToFile($thumb)) {
	error('cannot save thumbnail');
}

// redirect to the thumb
// note: you need the '?new' or IE wont do a redirect
header('Location: '.dirname($_SERVER['SCRIPT_NAME']).'/'.$thumb.'?new');

// basic error handling
function error($error) {
	header("HTTP/1.0 404 Not Found");
	echo '<h1>Not Found</h1>';
	echo '

The image you requested could not be found.

'; echo "

An error was triggered: $error

"; exit(); } //recursive dir function function mkpath($path, $mode){ is_dir(dirname($path)) || mkpath(dirname($path), $mode); return is_dir($path) || @mkdir($path,0777,$mode); }

Test it out!

Upload an image to yoursite.com/images/myimage.jpg

Open your web browser to yoursite.com/thumbs/100x100/images/myimage.jpg

Check in your thumbs folder, the file should actually be there now. Next time it is requested PHP will not be loaded.

Link to your thumbs like this:

<img src="/thumbs/100x100/images/myimage.jpg">

Clearing Cache

This is a small script I use to delete all the cached thumbs.

Upload an image to yoursite.com/thumbs/flush.php

delete_dir('./images');
echo 'done';

function delete_dir($path) {
	$files = glob($path.'/*');
	foreach($files as $file) {
		if(is_dir($file) && !is_link($file)) {
			delete_dir($file);
		}
		else {
			unlink($file);
		}
	}
	if ($path!='./images') rmdir($path);
}
Fork me on GitHub

Comments

Add new comment

hello , i hava an error like Not Found

The image you requested could not be found.

An error was triggered: invalid size

Hi there,

How does this differ from PHPThumb's own built-in caching function, what advantage does it offer?

Cheers,
Chris

Guest's picture

Thanks man! Works like a charm! I see the following speed performance. The original images are approx. 1024x768px. I make thumbs 200x200px. Previously it took something like 350ms to load one thumb. Now your script does it 3 times faster - about 130ms per a thumb!

Guest's picture

I am curious to know if anyone has successfully implemented any of the native PHPThumb Filters with Brett's script? I have tried a number of different syntaxes, but nothing has worked for me. I would like to use the UnsharpMask filter and based on the official PHPThumb readme file I thought something like this would work, but I've had no luck so far.

$phpThumb = new phpThumb();
$phpThumb->setSourceFilename($image);
$phpThumb->setParameter('w',$width);
$phpThumb->setParameter('f',substr($thumb,-3,3));
$phpThumb->setParameter('fltr[]','usm|80|0.5|3');
$phpThumb->setParameter('q','92');
if (!$phpThumb->GenerateThumbnail()) {
error('cannot generate thumbnail');
}
Guest's picture

Did you fix this? The correct usage is:

$phpThumb->setParameter('fltr','blur|1');

without the square brackets. I just used this on my application and it worked.

Guest's picture

Anybody experienced the "image is not loading on first attempt" behavior of phpThumb? Gives me some headaches...
Testing the image with a proxy (web-sniffer.net) tells that the returned status is 200 OK, but the Content-Length: 1062 is wrong. (and the browser can't show the image).

Guest's picture

If I understand you correctly, then yes. I have noticed this too. I am working around the problem by loading the image with style="display:none;" the first time. After that, the image loads perfectly every time. It is not an elegant solution, but it works for me.

Guest's picture

How to phpthumb lighttpd performance php 5.3.3

Hi Brett

I think changing this lines

if (!$phpThumb->RenderToFile($thumb)) {
error('cannot save thumbnail');
}

with this ones

if (!$phpThumb->RenderToFile($_SERVER['DOCUMENT_ROOT'].'/thumbs/'.$thumb)) {
error('cannot save thumbnail');
}

may help

Thank you for your great script

Guest's picture

Hi,

I'm getting weird problems. The first time i request a thumb, it is not shown - but thumb already exists in folder. But next time it works. No error,no nothing. But it is really frustrating. Any ideas?

Guest's picture

Hi,

I was getting errors at the RenderToFile stage due to $thumb only containing a relative path (images/pic.jpg) which phpThumb was plugging on to it's own path (therefore rendering to /phpThumb/600x600/images/pic.jpg instead of /thumbs/600x600/images/pic.jpg).

I fixed it by changing the RenderToFile path to an absolute but I'm sure some smarty pants can plug in a more universal approach without hardcoding /thumbs/ :)

// write the file
if (!$phpThumb->RenderToFile($_SERVER['DOCUMENT_ROOT']."/thumbs/".$thumb)) {
    error('cannot save thumbnail: '.$_SERVER['DOCUMENT_ROOT']."/thumbs/".$thumb);
}

Take care and thanks for the snippet :)

Guest's picture

First of all I want to say terrific blog! I had a quick question
that I'd like to ask if you do not mind. I was interested to find out how you center yourself and clear your mind before writing. I've
had trouble clearing my thoughts in getting my ideas out.
I do take pleasure in writing but it just seems like the
first 10 to 15 minutes are lost simply just trying to figure out how to begin.

Any recommendations or tips? Cheers!

Thanks oboote when I upgraded to the latest version of phpthumb I had that same error. Your code fixed it though, so now everything works fine in php 5.4 with phpthumb.

This rewrite code can also work on different webservers other than Apache.

I don't know the code for Nginx but I'm sure it's possible, but if anyone uses Lighttpd, you just build Lighttpd with Lua and then make a file like this:

"thumb.lua" in your Lighttpd directory.

-- little helper function
function file_exists(path)
  local attr = lighty.stat(path)
  if (attr) then
      return true
  else
      return false
  end
end
function removePrefix(str, prefix)
  return str:sub(1,#prefix+1) == prefix.."/" and str:sub(#prefix+2)
end

-- prefix without the trailing slash
local prefix = '/thumb'

-- the magic ;)
if (not file_exists(lighty.env["physical.path"])) then
    -- file still missing. pass it to the fastcgi backend
    request_uri = removePrefix(lighty.env["uri.path"], prefix)
    if request_uri then
      lighty.env["uri.path"]          = prefix .. "/index.php" 
      local uriquery = lighty.env["uri.query"] or "" 
      lighty.env["uri.query"] = uriquery .. (uriquery ~= "" and "&" or "") .. "thumb=" .. request_uri
      lighty.env["physical.rel-path"] = lighty.env["uri.path"]
      lighty.env["request.orig-uri"]  = lighty.env["request.uri"]
      lighty.env["physical.path"]     = lighty.env["physical.doc-root"] .. lighty.env["physical.rel-path"]
    end
end
-- fallthrough will put it back into the lighty request loop
-- that means we get the 304 handling for free. ;)
Guest's picture

whare Lighttpd directory.

Hey this is kind of of off topic but I was wondering
if blogs use WYSIWYG editors or if you have to manually code with HTML.
I'm starting a blog soon but have no coding experience so I wanted to get advice from someone with experience.
Any help would be enormously appreciated!

Guest's picture

hi sir. i keep on getting

Not Found

The image you requested could not be found.

An error was triggered: cannot save thumbnail

on my 2 separate servers. i already put the phpthumb.config.php but still same error, even with 0777 chmod.

Whatever I try I can't get this to work, it just keeps saying "cannot save thumbnail", any ideas?

Guest's picture

Try an earlier version of phpthumb. It looks like the new version has problems with relative paths to the images.

Guest's picture

Hi. Great job. I was working in my own phpThumb implementation, but I find yours is far better :)

I have a question, is there any way of doing a double redirection, in order to have a prettier url?

This would be what I'm trying to do:

/image/[some_folder/some_image]
to
/framework/thumbnails/[some_folder/some_image].jpg
    
and
    
/framework/thumbnails/[not found] 
to
/framework/controllers/my_img_processor.php?src=[some_folder/some_image.jpg]

Ok, I have the first rule and it works great. This is it:

RewriteRule ^image/some_folder/(.*)$ framework/thumbnails/some_folder/$1\.jpg [L]

But I can't find how to chain the second rule. I know how to do a generic 'not found' processing, but I don't know how to do it for that specific folder. Any help is appreciated.

I guess I can do it by placing your .htaccess in the '/framework/thumbnails/' folder, but I prefer to have all in the root .htaccess

A collateral question, do you think it's a bad idea to use the url thumbnails without the extension?

Thanks in advance.

Guest's picture

very nice job!

I add some lines, is it correct?

// ensure the image file exists
if (!file_exists($image)) {
$image = iconv('UTF-8','GB2312',$image);
$thumb = iconv('UTF-8','GB2312',$thumb);
if (!file_exists($image))
error('no source image');
}

Guest's picture

I'm having an issue getting this to work when the image filename has a space in it, e.g. 1819135014BHA 067-1.JPG

For some reason, whenever the image filename contains a space, I get the following errors:

ImageMagick failed with message (error : Unknown IO error convert: no data returned `http:///1819135014BHA 067-1.JPG'. convert: missing an image filename `jpeg://thumbs/pThumb5UvkV2'.)

Any ideas?

Guest's picture

May I suggest that this script also has the option of setting parameters per resize array.

// define allowed image sizes (((and parameters)))
$sizes = array(
'157x153'.'q=80'.'zc=1',
'600x600'.'q=90',
);

I guess, that it probably is going beyond a lot of things. But this script is so close to working perfect that it might be worth it. I like the fact that you can use this for other versions of phpthumb. Kinda like the phpthumb.gxdlabs.com

Unfortunately, everyone is talking about deleting the entire cache directory and then recreating another one. If you are on a shared server with SSH access you will have to wait for ages to delete the huge cache directory via ftp. I was looking for a script a solution which automatically deletes the content of the cache directory periodically (that's the way it should work isn't it?)

Guest's picture

Hi there. I love this script, but cant make it work, except if i call it like this: http://sofuscomer.com/thumbs/306x204/fto/msprojects/msproject_255.jpg. This works and it even creates all the folders and the cached thumbnail.

But if i call it from within my page nothing happens.
E.g.;
.jpg" />

I have the latest phpthumb.sourceforge and have triple checked my paths.

Could somebody give me a hint.

.htaccess is set exactly as tutorial suggests

Its most curios!

PS, to the person who asked about zc=1
Simply add this in your thumbs/index.php file:

$phpThumb->setParameter('f',substr($thumb,-3,3)); // set the output format
//$phpThumb->setParameter('far','C'); // scale outside
//$phpThumb->setParameter('bg','FFFFFF'); // scale outside
$phpThumb->setParameter('zc','1'); // ZOOM CROP
$phpThumb->setParameter('q','91'); // Quality 0-100

This would be fantastic if I can implement this!
Our heavily trafficed site is chewing through a lot of memory at peak load times.
BUT there is something fundamental I'm not getting with implementing your solution :(

How do we implement an image url such as:

http://127.0.0.5/wp-content/uploads/userphoto/8_0f5c7160016d7a75f619ca67...

Our phpthumb urls currently look something like:

http://127.0.0.5/phpThumb/phpThumb.php?src=http://127.0.0.5/wp-content/u...

hence does that mean the url should be rewritten as:

http://127.0.0.5/thumbs/150x150/images/http://127.0.0.5/wp-content/uploa...

Will the script automatically pull our images from the original upload location, creating the sizing folders automatically on the fly?

Sorry if this seems lie a stoopid Q, but our images are not appearing hence we obviously have the pathing wrong? We don't have to manually copy any existing files anywhere do we, since the images will get copied into the thumbs dir only when and if they are requested?

Many thanks!

Thanks for the the script. It really saved my day.

Guest's picture

I LOVE YOU! :)
you save my life, thank you very much!

Guest's picture

To keep the script safe from abuse and giving me freedom to easily set any image size in my templates, I removed:

if (!in_array($size,$sizes)) {
error('invalid size');
}

and added this:

if (!strstr( $_SERVER['HTTP_REFERER'],$_SERVER['SERVER_NAME'])) {
error('bad request');
}

Guest's picture

Thanks for the suggestion, however I would not personally use that method. Some browsers and security programs cause the referring site to not be sent and the referring site can easily be spoofed.

brett's picture

To keep the script safe from abuse and giving me freedom to easily set any image size in my templates, I removed:

if (!in_array($size,$sizes)) {
error('invalid size');
}

and added this:

if (!strstr( $_SERVER['HTTP_REFERER'],$_SERVER['SERVER_NAME'])) {
error('bad request');
}

Guest's picture

Everything sorted out now...i had to add the "zc" zoom crop parameter to get it to exact dimensions!

thanks for this great piece of code Brett! works like a champ!!

best wishes

Guest's picture

Can you give us some tutorial how you add "zc" zoom crop parameter please?

Thank you!

Guest's picture

okay i fixed it!!....everything works nows finally.......just one minor thing.....some of the images are not the exact 160x120 dimensions.....some are <120x90depending if they are portrait or landscape images.....if they are portrait...the thumbnails fall short of width=160 but have the right height....if they are landscape....some fall short of height=120 but have the right width

Guest's picture

perhaps enable these settings?

//$phpThumb->setParameter('far','C'); // scale outside
//$phpThumb->setParameter('bg','FFFFFF'); // scale outside

if not you will need to refer to the phpthumb docs on how to get the image exactly as you want it. Let me know how you go

brett's picture

when i visit index.php directly......i get the same thing....it just shows the code in the browser.  Pretty much whatever code that is in the index.php file will show in the browser window 

Guest's picture

awesome the code up top worked and i got the structure, but the index file will not generate the thumbnailwhen i visit the url in the browser (/thumb/wp-content/uploads/2009/03/myimage.160x120.jpg), nothing happens and the index.php code shows......is there anything else i am forgetting?   

Guest's picture

sounds like apache is not parsing the file with php.  What happens when you visit index.php directly, and pass it arguments like  index.php?thumb=wp-content/uploads/2009/03/myimage.160x120.jpg  ?

brett's picture

Hi Brett, thanks for the fast reply....

my problem is i don't know how to structure the call to insert the "dimensions" in between the image and .jpg.....my call outs are as follow

Generating Thumbnails
********************************************************************/

function show_thumb($width,$height,$default_image) {

global $post;
$custom_field_value = get_post_meta($post->ID, 'Thumb', true);
$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => 1) );

if ($custom_field_value == true) {

$tweak = str_replace('/', '%2F', $custom_field_value);
$img_url = str_replace(':', '%3A', $tweak);
print 'post_title.'" alt="'.$post->post_title.'" />';

} elseif ($attachments == true) {

foreach($attachments as $id => $attachment) {
$img = wp_get_attachment_image_src($id, 'full');
$img_url = parse_url($img[0], PHP_URL_PATH);
print 'post_title.'" alt="'.$post->post_title.'" />';
}

} elseif ($default_image == true) {

print '';

} else {

// do nothing

how would i code it to call the structure with the dimension in between the filename and extension

also can someone help me with filename parsing.....in the else if (attachment)...it would take the full source url and strip out the domain root and leaves the url "/wp-content/uploads..etc".....but when i use the "if" custom value...it uses the full url "http://www. etc"....i tried adding $img_url = parse_url($img[0], PHP_URL_PATH); to the first IF box but does not work

thanks!

Tien

Guest's picture

Hey Tien,

You can use the CODE tag to post tag. I altered your comment.

I haven't tested this code, but it should be a push in the right direction for you.


$img_array = explode('.',$custom_field_value); // break the image apart at the dots
$ext = array_pop($img_array); // pop the last element off the array to get the image extension
$thumb_url = implode('.',$img_array).'.'.$width.'x'.$height.'.'.$ext; // rejoin to create the thumb url
print ''; // print the image

Hope that helps.

brett's picture

If you have animated gif images and use this code you'll notice there never animated. I have found a fix though, simply by adding these 2 lines of code, you'll be animated again.

find:

list($width,$height) = explode('x',$size);

and add the following code below after it:

$ext = substr($thumb,-3,3);

then find:

$phpThumb->setParameter('h',$height);

and add the following code below after it:

$phpThumb->setParameter('f',$ext);

See this works because the "F" parameter in "phpThumb" stands for "output image format" but by default the output format is jpg. This code grabs the last 3 letters of the file extension from the "$thumb" variable and then sets the "output image format" with it.

Now don't worry if you have a 4 digit file extension like .jpeg because if the "F" parameter get's "peg", sent to it, then it just goes back to the default "output image format", which is jpeg anyways. Enjoy.

Guest's picture

Thanks goldcard, I added that into the example.

brett's picture

Thanks for this fix!!!

Here is just a little method to change the name of your pictures if you read the picture name from a database:

class thumbhelper
{

/**
* Prepares the picture for using the thumb caching
* features by phpThumb and the thumbs hack by brett.
*
* Basically it takes a normal picture (e.g. "resort_1_pic_10.jpg")
* and adds the location and the desired size of the picture so
* the Apache directive can find it.
*
* Example:
*
* resort_1_pic_10.jpg =>
*
* /thumbs/images/resorts/resort_1_pic_10.450x300.jpg
*
* @param $location Location of the picture (e.g. "/thumbs/images/resorts")
* @param $thumbSize Size of the desired picture (e.g. "450x300")
* @param $pictureName Name of the picture (e.g. "resort_1_pic_10.jpg")
*
* @return thumbs ready picture name
*/
function addThumbSize($location, $thumbSize, $pictureName)
{
$thumb_array = explode('.', $pictureName);
return $location.$thumb_array[0].".".$thumbSize.".".$thumb_array[1];
}

}

thanks for this.
Only just worked out how to work my htaccess file so this was a big help

Guest's picture

Thanks so much for this, the answer to many hours of hair loss!!! Works a treat.

Guest's picture

Thanks a lot for this script. Only thing you need to edit is this line:

// write the file
if ($phpThumb->RenderToFile($thumb)) {
error('cannot save thumbnail');

it should actually be this:

// write the file
if (!$phpThumb->RenderToFile($thumb)) {
error('cannot save thumbnail');

the way you had it would give every image a cannot save thumbnail error message before it, saved the thumbnail. Also I'd like to say that the mkdir fix works.

Guest's picture

thanks, i have fixed this in the example.

brett's picture

I've created the thumb directory and set the permissions to 0777 but I always get the error "cannot create directory"

I have an already existing library of images located at /gallery/images and then cataloged by numbered directory. So an image I was trying to test for example is located at /gallery/images/2/2.jpg

When I enter /thumb/gallery/images/2/2.50x50.jpg I get the cannot create directory error
It should create the folder /thumb/gallery/images/2/ and place the thumb in there correct?

I copied phpThumb to /phpthumb, created the /thumb directory with the .htaccess file and index.php file inside and chmod it 0777. Is there a config step I missed? FWIW I have been using phpThumb for quite a while with no problems, besides the performance issues you described which is why I'd love to get this working :)

Guest's picture

Found a fix for cannot create dir.

Replace:

// make the directory to put the image
if (!@mkdir(dirname($thumb),0777,true)) {
error('cannot create directory');
}

With:

//recursive dir function
function mkdir_recursive($pathname, $mode)
{
is_dir(dirname($pathname)) || mkdir_recursive(dirname($pathname), $mode);
return is_dir($pathname) || @mkdir($pathname,0777,$mode);
}

if (!mkdir_recursive(dirname($thumb),true)) {
error('cannot create directory');
}

Should work fine now.

Guest's picture

thanks for the fix, i have added it to the example.

brett's picture

Thanks for your post, it's just what the doctor ordered. I use phpthumb within expressionengine and have noticed as I pile more sites onto my shared server, my gpu count is rising rapidly per month. Having a few issues though.

When I first run the script I see this error:
Not Found

The image you requested could not be found.

An error was triggered: cannot save thumbnail

If I refresh again the thumbnail shows up correctly. If I try and do this for another image (now that the directory structure has been created from the previous image), this error is displayed:
Warning: mkdir() [function.mkdir]: File exists in C:\site\thumbs\index.php on line 59
Not Found

The image you requested could not be found.

An error was triggered: cannot create directory

I'm running wamp on windows 7, but have also found the same errors on the production server. If I delete the file and directories created for the first thumbnail, I can recreate above errors. Any ideas where I might be going wrong?

Guest's picture

If it cannot save the thumbnail then $phpThumb->RenderToFile($thumb) is failing. I assume it is to do with your mkdir not creating the full path. Perhaps it is just creating 1 folder per run. So if you have an image 3 folders deep it would take 3 refreshes to generate. Would you be able to confirm this?

To remove the second error (Warning mkdir), just put an @ in front of mkdir. I have now done this in the demo code above.

brett's picture

So if you have an image 3 folders deep it would take 3 refreshes to generate. Would you be able to confirm this?

No luck, no matter how many times I refresh is still gives me the cannot create directory error. I'm running php 5.2.9-2

To remove the second error (Warning mkdir), just put an @ in front of mkdir. I have now done this in the demo code above.

Confirmed it fixes the 2nd error. Thanks!

Guest's picture

Hi Rick,

Does it create the folder to put the image in?

If YES:
The problem is the phpThumb is failing to render the image. print_r($phpThumb) may give some insight.

if NO:
not the problem is the mkdir is failing. www.php.net/mkdir

brett's picture

Nice script, one main modification... if using this with certain other modrewrite settings (e.g. replacing php files with fake directories etc) the include needs to be relative from the document root, rather than relative from the current page.

To do this replace the line :
require('../phpthumb/phpthumb.class.php');

with the more generic:

require($_SERVER['DOCUMENT_ROOT'] . '/phpthumb/phpthumb.class.php');

Hope that helps

Guest's picture

Couple of typos I found when setting up:

In the following block:

// redirect to the thumb
// note: you need the '?new' or IE wont do a redirect
header('Location: /thumbs/'.$thumb.'?new')

You forgot a semicolon on the end.

Also, in your instructions it says to create a directory called "thumbs", and refers to that directory all the way through, but the code refers to "thumb", and for me it only worked with a directory called "thumb".

That aside - what fantastic work! We've just launched a site which used phpthumb heavily, and it crashed the server hard. Hoping that this may help us reduce the load enough that it can cope.

Guest's picture

Hi Jaymis, Thanks for the tip, I have added the semicolan.

The script should work in any folder. You should be able to name it whatever you like. The only thing forcing it to be /thumbs/ is the redirect in the line you pointed out.

brett's picture

Just tried this with a few modifications and it's working lovely wtih ExpressionEngine. Thanks Brett

I've got this script working, but I'm having trouble with files that are multiple folders deep like:
http://server.com/thumbs/index.php?thumb=/projects/gallery_albums/type/n...

Presumably it's trying to mkdir (/projects/gallery_albums/type/). Is there a way I can work around this?

Thanks Brett, great script. I just wish phpthumb would solve this in some way, it's a huge pain that the cache is so slow.

Guest's picture

Thanks for the feedback on the security issue.

I added an $allowed array to ensure only the specified sizes can be created.

brett's picture

I had something similiar implemented in one of my projects but removed it
later because this may open up your webapp for (D)DoS attacks (which are farely seldom).

Imagine somebody requesting these:
yoursite.com/thumbs/images/myimage.100x100.jpg
yoursite.com/thumbs/images/myimage.100x101.jpg
yoursite.com/thumbs/images/myimage.100x102.jpg
yoursite.com/thumbs/images/myimage.100x103.jpg
and so on...

Every time the image is parsed, loaded into memory (MEM), resized (CPU)
and stored (IO, DISKSPACE). A workaround is to define a set of fixed dimensions e.g.
'small' => array(50,50), 'large' => array(500,500) and allow only those to
be used.

- David Persson

Guest's picture

GREAT! I love it!

Guest's picture

Feeling social? Share this page!