Upload file to a folder inside the root folder with PHP

Asked

Viewed 274 times

1

Based on the PHP documentation code on fileupload I created the following code:

<?php
$uploaddir = './novo/side';
$uploadfile = basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Arquivo válido e enviado com sucesso.\n";
  } else {
 echo "Possível ataque de upload de arquivo!\n";
}

   echo 'Aqui está mais informações de debug:';
   print_r($_FILES);

   print "</pre>";

?>

So far so good, when I use the HTML form it takes the file and brings it to the Project Root, the problem is that I want it to go to a folder that is inside the root called side.

$uploaddir = './novo/side';

The result I have is that the file is only in the folder novo.

In the tests I released the inherited share so that there was no impediment to access the folders.

I am using Windows with Wampserver.

  • I tried that already but not sure either, it keeps sending to the root.

1 answer

2


In function move_uploaded_file you’re moving it to:

$uploadfile = basename($_FILES['userfile']['name']);

Then the right thing in your case would be:

$pasta = $uploaddir."/".$uploadfile;
move_uploaded_file($_FILES['userfile']['tmp_name'], $pasta)
  • So from what I understand it would include the line $pasta = $uploaddir."/".$uploadfile; and the line of move_uploaded_file would look that way if (move_uploaded_file($_FILES['userfile']['tmp_name'], $pasta)) {. I tried and it didn’t work.

  • Like this is an example for you to understand the process, the code is your you do not need to add this new variable, but you have to understand how the script is working... If you put as suggested by Marcelo: $uploadfile = $uploaddir."/".basename($_FILES['userfile']['name']) then you don’t need this new variable $pasta... The important thing for your learning and you see how the script runs through each line and what it does... Good luck man :) any doubt goes commenting...

  • There’s an interesting point. I had understood that if I put $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);that way I only have the addition of the folder name in the file name and with that keeps going only to the root.

  • But you need the / then stay : $uploadfile = $uploaddir."/".basename($_FILES['userfile']['name']), drew?

  • I’m sorry for the lack of understanding, I started studying now and I realized I was missing / it composes the end of the address, but now I have a folder access problem in Windows. I will solve here.

  • That’s what I’m... Good Luck any question do not hesitate to create a new question, if any of the answers is correct, consider validating it by clicking on the green incon below the evaluation arrows.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.