开发者

View images in browser with no extension

开发者 https://www.devze.com 2023-02-15 01:32 出处:网络
I have a directory in my web app where I want to keep all the user profile pictures. Users can u开发者_开发百科pload all types of images (png, jpg, gif). However, I want the image URL to be friendly,

I have a directory in my web app where I want to keep all the user profile pictures. Users can u开发者_开发百科pload all types of images (png, jpg, gif). However, I want the image URL to be friendly, eg. http://example.com/static/picture/300-username, where the file is 300-username, but with no extension. I thought of removing the extension when the user uploads, and with a PHP controller, add a:

header('Content-Type: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png');
readfile('http://example.com/static/picture/300-username');

This has worked well. I was wondering however, if this can be done by placing an .htaccess file in the picture directory, with some sort of Header, that whatever file is read in this directory, will display as picture. Is this possible?


Don’t remove the extension, just offer extensionless URIs like /static/picture/300-username. Then add a line to your .htaccess:

Options +MultiViews

Apache will set the correct content type for you. See the documentation for Content Negotiation.


You can't specify multiple Content-Type like that.. You need to pass the correct header for each image served:

<?php
    $user = '300-username';
    $picture = 'http://example.com/static/picture/' . $user;
    $info = getimagesize($picture);
    $fp = fopen($picture, "rb");
    if ($info && $fp) {
        header("Content-type: {$info['mime']}");
        fpassthru($fp);
        exit;
    } else {
        // error
    }
?>

(Code adapted from PHP's getimagesize() documentation.)


First your path need to be physically existent, else I don't think Apache can do anything for you.

However, here may be a workaround using a RewriteRule, keep the extension (by the way, I think it's bad practice to remove extension of a file, especially when they are not plain text files), and accept a requested file like 300-username to rewrite to 300-username.jpg.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号