提供图像? htaccess重定向图像文件夹?

时间:2012-09-17 12:42:22

标签: php image .htaccess hash serving

我有一个上传图像的php脚本,将其重命名为随机哈希,根据哈希创建文件夹,将原始图像存储在最后创建的文件夹中,最后为其创建2个其他缩略图... < / p>

常规图片... images/a3c/65c/297/108_a3c65c2974270fd093ee8a9bf8ae7d0b.jpg

缩略图... images/a3c/65c/297/108_a3c65c2974270fd093ee8a9bf8ae7d0b_t.jpg

较小的缩略图... images/a3c/65c/297/108_a3c65c2974270fd093ee8a9bf8ae7d0b_sm.jpg

对于每张上传的照片,它会在数据库中存储一条新记录,其中包含照片ID和此信息

/a3c/65c/297/108_a3c65c2974270fd093ee8a9bf8ae7d0b

(注意我没有存储“.jpg”或“_t.jpg”等)

现在为了让我服务图像(我不知道这是一个好习惯),目前我有这个PHP功能,返回图像...

function get_image($image_id,$type = '')
{
    $sql = "SELECT * FROM photos where photo_id = {$image_id}";
    $query = $this->db->query($sql);
    $r = $query->row();

    $image = base_url().'images/'.$r->dir_1 . '/' . $r->dir_2 . '/' . $r->dir_3 . '/'.$image_id.'_'.$r->img_hash;

    if($type == 'small')
        return $image.'_sm.jpg';
    if($type == 'reg_thumb')
        return $image.'_t.jpg';
    if($type == '' || $type == 'original')
        return $image.'.jpg';

}
基本上,我想做一些像twitter这样的图片网址就像这样的内容

https://twimg0-a.akamaihd.net/profile_images/2392722244/blah.jpg

问题...

  1. 我怎样才能实现这种类型的url结构? htaccess的?
  2. 我是否以正确的方式返回图像?
  3. 是我在做什么安全,聪明和良好的做法?如果不是有更好的方法吗?
  4. 谢谢!

1 个答案:

答案 0 :(得分:1)

IMO, 你肯定可以用url重写来做到这一点。 在/ etc / apache2 / sites-available / yoursite中,

    <Directory />

            RewriteEngine On
            RewriteCond %{HTTP_REFERER}          profile_images/(\w+)/(\w+|.)+$


            RewriteRule ^/profile_images/(\w+)/         index.php?image_id=$1 [L,QSA]

            Options Indexes FollowSymLinks MultiViews
            AllowOverride None

            Order allow,deny
            allow from all
    </Directory>

尝试玩弄它。我认为它在htaccess中是非常相似的指令。

Am I returning the images the right way?

你是什么意思?你的“回归”将起作用。我会使用switch / case语句而不是ifs。

is what im doing safe, smart, and a good practice? if not is there a better method?

安全:你应该逃避你的输入。但是,如果仅重定向图像名称是字母数字,则不应该是一个问题

我不知道为什么你会分解成这么多目录。每个图像一个目录+缩略图就足够了。不要担心使用b-tree或类似的东西进行索引,只在db中使用索引就足够了。

最后但并非最不重要的是,如果我不需要在用户和图像之间建立链接,我只会使用apache的重写规则来实现这一目标。

RewriteRule ^ / profile_images /(\ w +)(_ \ w +)?.(jpg | png)/ images / $ 1 / $ 1 $ 2. $ 3

它不涉及php或db,并且在一行中完成。

https://serverfault.com/questions/214512/everything-you-ever-wanted-to-know-about-mod-rewrite-rules-but-were-afraid-to-as

http://httpd.apache.org/docs/current/mod/mod_rewrite.html

我不确定这是否有帮助,但你可能已经学会了一些东西。至少,你有另一种观点:)

相关问题