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 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch