2

I've looked around here for similar question but couldn't find any that solved my problem. I want to upload a file to a folder just above the web root (www folder). I'm running wamp on windows. Please how do I achieve this? Thanks.

Russell Troywest
  • 8,635
  • 3
  • 35
  • 40
Chibuzo
  • 6,112
  • 3
  • 29
  • 51
  • 1
    Like any other upload... then just move the file to the desired location. [PHP manual on POST uploads](http://www.php.net/manual/en/features.file-upload.post-method.php) – Pekka Mar 22 '12 at 17:40
  • reference this question: http://stackoverflow.com/questions/223800/how-can-i-relax-phps-open-basedir-restriction – NDBoost Mar 22 '12 at 17:40

2 Answers2

4

By default files will be uploaded well above the web root for security and you have to move them to wherever you want. Take a look at move_uploaded_file().

Have a look at print_r($_FILES) and it will show you the location of each file you have uploaded.

472084
  • 17,666
  • 10
  • 63
  • 81
  • I don't want to reconfigure my apache server because I do not have that privilege on my hosting server, I've used move_uploaded_file() to move file into my web root, but now I want them to move to a name directory just above the web root. – Chibuzo Mar 22 '12 at 17:57
  • you can move it to whatever folder you need, just change the second parameter in move_uploaded_file() – 472084 Mar 22 '12 at 18:02
  • Yes I know I can, I tried this $upload_folder = "../../matrials/"; because the upload script is in a file that is inside a folder inside the document root (mywebsitefolder/user/the-upload-script.php). the folder "materials" is just above my web root, i.e materials/www/ I don't know what else to try. Thanks for your time – Chibuzo Mar 22 '12 at 18:22
  • 2
    Give it a full path like: `$_SERVER['DOCUMENT_ROOT'].'/www/'` - you should use a relative path – 472084 Mar 22 '12 at 18:23
  • Just to clear something up, my last comment should say "shouldn't" ;) – 472084 Mar 23 '12 at 09:11
2

This is similar to what I use for images uploaded via forms. This is presuming the input field has a name of 'image'.

function getExtension($str) {
    $i = strrpos($str,".");
    if (!$i) { return ""; }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);
    return strtolower($ext);
}    

// Get the extension of the uploaded file
$ext = getExtension($_FILES['image']['name']);

// Give the file a new name (if you need) and append the extension.
$img_name = time().$ext;

// Set destination for upload
$new_image = "./images/uploaded/" . $img_name;

// Copy the file to the new location
$copied = copy($_FILES['image']['tmp_name'], $new_image);

You can use this for any file uploaded, as the previous answer stated, doing a var_dump($_FILES) will show you everything you need to know about your uploaded file before you do anything with it.

David Barker
  • 14,484
  • 3
  • 48
  • 77