dtzd65908 2010-10-04 10:57
浏览 39
已采纳

如何使用php为用户上传的文件设置自定义URL

How can i offer custom url's for files uploaded by users.

For ex: user uploads a file called stack.png and it's uploaded on directory http://www.website.com/uploads/stack.png

But i want to allow the user to view/download the same file at http://www.website.com/username/uploads/stack.png

Please note i don't want to use url shortening/changing scripts, I want to somehow map the file url to that location., such that user can insert the file in their website or blog using the url "http://www.website.com/username/uploads/stack.png" instead of "http://www.website.com/uploads/stack.png"

Is it possible?? If yes how can i do it using php.

Please note i have hundreds of files for which i want to implement tis.

  • 写回答

2条回答 默认 最新

  • dongsou8980 2010-10-04 11:26
    关注

    The question you're asking is not easy to answer quickly. There isn't a simple PHP based solution you can copy and paste in 5 seconds. The feature you're suggesting usually implies some form of URL rewriting, a routing scheme, or functionality to that effect.

    Also on a site with thousands of users, maybe where each user can upload many files, you have to start thinking about how you store the files files in the file system. Thousands of files in a flat directory just won't cut it.

    Okay. Here is a naive example of how you could start solving this:

    Let's say you actually store the files in the form:

    /uploads/<username>_<filename>.<extension>
    

    Read about mod_rewrite and create a rewrite rule on your webserver like this:

    RewriteRule ^(.*)/uploads/(.*) getfiles.php?username=$1&file=$2
    

    This will allow you to use URL's like

    /<username>/uploads/<filename>.<extension>
    

    Create a php script named 'getfiles.php' and return the file like so

    <?php
    
    $path = '/uploads/'.$_GET['username'].'_'.$_GET['file'];
    
    if (!file_exists($path)) {
        die(
            "OMFG! The user tried to access a file that doesn't exist. " .
            "I think I'm gonna die!"
        );
    }
    
    header('Location: '.$path);
    

    But remember: this is only one of many ways to implement something like this. I chose this way of doing it just because it is so simple to implement. An experienced developer would not implement it this way. But it should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统