开发者

How to have custom url for user uploaded files using php

How ca开发者_StackOverflow社区n 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.


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.


You can Use the Alias Match Directive in your VHost Config: AliasMatch ^/[^/]+/(.*) /usr/local/uploads/$1

more information at http://httpd.apache.org/docs/1.3/mod/mod_alias.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜