Jump to content

Redirecting image hotlinking with PHP?


tyler22

Recommended Posts

Hey everyone. I host a website where users can upload pictures, flash animations, etc.

 

When a user uploads a file, it goes to the /uploads/ folder. So, an example link might be something like this...

 

www.site.com/uploads/565455image.jpg

 

A couple days ago I did a bit of reorganizing using mkdir and a php script I created, and now all of the files have been put into folders corresponding to the date that they were uploaded. Example...

 

www.site.com/uploads/5_3_2010/565455image.jpg

 

Obviously, anyone using the site to host their forum signatures and such now have broken images.

 

Is there a way to get data from the first one (specifically the 565455 number), make an sql query using this number to retrieve the NEW file path, and display that image instead? If so, can anyone point me in the right direction?

 

(I realize this will probably be using some form of Rewrite and an .htaccess)

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/232605-redirecting-image-hotlinking-with-php/
Share on other sites

Let's say this is your .htaccess file inside /uploads/:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^[^/]*$ /uploads/getfile.php [L]

 

Now every time someone requests a file in /uploads/ (and not in any subfolder) that doesn't exist, your php file /uploads/getfile.php gets called. In that php file you can use $_SERVER['REQUEST_URI'] to get the file requested, look it up in the database, etc. Just make sure to set the response status to 404 if the file actually doesn't exist.

 

As for getting that number in front of the file, I'm guessing this would suffice.

$urlinfo = parse_url($_SERVER['REQUEST_URI']);
$pathinfo = pathinfo($urlinfo['path']);
$imgid = 0;
if(preg_match("/(\d{1,6}).*\./", $pathinfo['basename'], $matches)) {
    $imgid = $matches[1];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.