--- timthumb.php 2011-08-02 08:15:25.000000000 -0700
+++ timthumb.new.php 2011-08-02 11:35:23.000000000 -0700
@@ -611,6 +611,17 @@
return preg_match ($pattern, $url);
}
+/**
+ *
+ * @param string $file path to file to be unlinked
+ */
+function timthumb_shutdown_unlink( $file ) {
+ if ( !file_exists( $file ) )
+ return;
+ if ( !is_writable( $file ) )
+ return;
+ @unlink( $file );
+}
/**
*
@@ -624,6 +635,11 @@
// work out file details
$filename = 'external_' . md5 ($src);
+ // create a temporary file outside the webroot which will be safer to work with on properly configured servers
+ $temp_path = tempnam( sys_get_temp_dir(), 'timthumb-' );
+ // and make sure we clean up our temporary file on shutdown
+ register_shutdown_function( 'timthumb_shutdown_unlink', $temp_path );
+ // define where, if all goes well, the file should end up after security checks
$local_filepath = DIRECTORY_CACHE . '/' . $filename;
// only do this stuff the file doesn't already exist
@@ -671,7 +687,7 @@
global $fh;
- $fh = fopen ($local_filepath, 'w');
+ $fh = fopen ($temp_path, 'w');
$ch = curl_init ($src);
curl_setopt ($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);
@@ -684,25 +700,21 @@
curl_setopt ($ch, CURLOPT_WRITEFUNCTION, 'curl_write');
// error so die
- if (curl_exec ($ch) === FALSE) {
- unlink ($local_filepath);
- touch ($local_filepath);
+ if (curl_exec ($ch) === FALSE)
display_error ('error reading file ' . $src . ' from remote host: ' . curl_error ($ch));
- }
curl_close ($ch);
fclose ($fh);
// check it's actually an image
- $file_infos = getimagesize ($local_filepath);
+ $file_infos = getimagesize ($temp_path);
// no mime type or invalid mime type
- if (empty ($file_infos['mime']) || !preg_match ("/jpg|jpeg|gif|png/i", $file_infos['mime'])) {
- unlink ($local_filepath);
- touch ($local_filepath);
+ if (empty ($file_infos['mime']) || !preg_match ("/jpg|jpeg|gif|png/i", $file_infos['mime']))
display_error ('remote file not a valid image');
- }
+ // move the temporary file to where we expect it to be
+ copy( $temp_path, $local_filepath );
} else {
if (!$img = file_get_contents ($src)) {
@@ -861,4 +873,4 @@
echo '<br />TimThumb version : ' . VERSION . '</pre>';
die ();
-}
\ No newline at end of file
+}