views:

39

answers:

3

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.

A: 

Unable to comment, so here's my answer.

@Pekka For ex: lets just say i add user id before file name so it becomes 234stack.png I used this structure for making things easier, the url is even more complex.

@thomasmalt well, i can create directory for every user, but what if i have thousands of users???

Dhruv Kumar
You would be able to comment if you'd use your original account. I would switch over to that and add the new info into the question
Pekka
I can comment now (relogged in), so, do you know how can i implement this???
Roccos
+1  A: 

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.

thomasmalt
+1  A: 

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

Hannes
Good answer. +1 from me.
thomasmalt