Rewrite Images to php script mod_rewrite

Discussion in 'Apache' started by nosf009, Nov 15, 2009.

  1. #1
    Hello, and thank you in advance if you help out, I have a slight of a problem here.

    I have a folder with pics.
    What I would like to do is when someone loads in a browser:
    http://www.domain.com/images/test.jpg (or png, gif)
    that actually
    http://www.domain.com/script.php?image=test.jpg is loaded.

    But, that's okay, I've been successful at making rewrite which makes that.
    Thing is, script should look like this: (simplified)

    echo "<img src='./images/".$_GET["image"]."' />";
    PHP:
    But when I do that, picture is again rewritten or something and, in short, I cannot do that.

    What can I do here? I suck at regex and don't know how to perhaps, dunno, make rewrite work only in images directory but not in folder below. Or, is this doable at all?
    Google-ing didn't help as I don't know exactly what I'm looking for.

    Please help.
    Cheers
     
    nosf009, Nov 15, 2009 IP
  2. tolra

    tolra Active Member

    Messages:
    515
    Likes Received:
    36
    Best Answers:
    1
    Trophy Points:
    80
    #2
    Assuming you are trying to make the script deliver the image then you need to loose the echo of the <img> tag and instead make the script send the image data direct:

    <?php
    
    // Check image parameter present and sane to some degree
    // Check image file exists
    $ext = array();
    if(!isset($_GET['image']) || !preg_match('/^[a-z0-9_-]+\.(png|jpg|gif)$/i', $_GET['image'], $ext) || !is_readable($_GET['image'])) {
    	// Data not valid issue 404 and stop
    	header("HTTP/1.0 404 Not Found");
    	exit;
    }
    
    header("Content-Type: image/$ext[1]");
    header("Content-Disposition: filename=\"" . $_GET['image'] . "\"");
    readfile($_GET['image']);
    
    ?>
    Code (markup):
    The above code takes 1 parameter image which is the image to return and works with .jpg, .gif and .png, it does some tests to make sure the request is sane but I'll leave it up to you to make sure it's secure enough for your needs. The .php script must be in the same folder as the images it's returning, however it would be trivial to make it load the images from anywhere in the file system including outside of public_html.
     
    tolra, Nov 16, 2009 IP