How to Fix Timthumb using a Virtual Directory (URL contains tildes (~))

The timthumb tilde issue has been discussed for almost a year now on the official timthumb site, and the developers have yet to do anything to provide a fix for users in development environments.

The issue is that when developers are developing sites using a URL structure such as: http://127.0.0.1/~mysite/images/dog.jpg, timthumb does not correctly parse the folder structure and returns a broken image. In this case, a proper path might be: /home/mysite/publichtml/images/dog.jpg, however timthumb creates the broken path: /home/mysite/publichtml/~mysite/images/dog.jpg.

For the record, I believe timthumb is a horrible idea and should be avoided at all costs (security and performance issues). However there are many instances where you might purchase a template to find it is completely integrated with timthumb, and the amount of time it could take to remove timthumb from the template is not worth it.

How to fix

Make sure you are using the latest version of timthumb. At the moment of this writing, the version is 2.8.5

At line 209 you will find the code:

$this->src = $this->param('src');

Replace that with:

//check if tilde is found in src if(strstr($this->param('src'),'~')) { $urlparts = explode('/',$this->param('src')); foreach($urlparts as $urlpart) { //do not include any part with a ~ when building new url if(!strstr($urlpart,'~')) { $newdevurl .= $urlpart.'/'; } } //remove trailing slash $newdevurl = substr($newdevurl,0,-1); $this->src = $newdev_url; } else { $this->src = $this->param('src'); }

This isn’t the most elegant solution, however the only time you should be using it is while you are developing and debugging the site (tildes should never be in the URL of a live website). Once you go live, it will automatically skip over that extra processing and work just as timthumb is intended.

Additional fix for $SERVER[‘DOCUMENTROOT’]

There might be a chance that timthumb is still not working, and that could be because $SERVER[‘DOCUMENTROOT’] is not being properly defined. To get around this, we need to manually define $SERVER[‘DOCUMENTROOT’] at the beginning of the document:

Above this line (line 23):

define ('VERSION', '2.8.5');

Insert the root path of your website, something like this:

$SERVER['DOCUMENTROOT'] = '/home/mysite/public_html/';

I hope that helps, and if it is still not working for you, I highly recommend visiting the official timthumb website and talk with the developers.