0

I want to save an uploaded image to a folder up in the directory. I have tested these destinations: $destination_path = __DIR__."/../img/"; and $destination_path = "../img/"; and $destination_path = "/../img/";

I also tried the following and it does not work

chdir('../img/');
$destination_path = getcwd().DIRECTORY_SEPARATOR;

Only this worked for me only if the file is placed in the website main directory!!:

 $destination_path = getcwd().DIRECTORY_SEPARATOR;

My code:-

$destination_path = "/../img/";
$name = rand (100,1000);
$result = 0;
$filename=$_FILES['myfile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION) ;

   // setting up the directory of the file uploaded
$target_path = $destination_path . $name .".". $ext;

   //making sure the file has been uploaded in the specified directory
if(@move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) 
 {
 $result = 1;
 }
Sami Al-Subhi
  • 4,406
  • 9
  • 39
  • 66
  • @Kaddath I updated the question. – Sami Al-Subhi Jan 08 '18 at 08:48
  • 1
    Do you have an error or warning if you remove the error suppression `@` from `move_uploaded_file`? (why is it here in the first place? this is the kind of function you'd want to know if something goes wrong) – Kaddath Jan 08 '18 at 09:13
  • There is no error when I use your suggestion and remove `@`. I use it because the file return a json with some data including `$result` that would indicate if `move_uploaded_file` worked or not without the actual error reporting. – Sami Al-Subhi Jan 08 '18 at 09:27
  • As read through the net, it seems easy and straight forward function to use but here it does not work. Only `$destination_path = getcwd().DIRECTORY_SEPARATOR;` works if php file is placed in main directory so that the images are all uploaded to the main directory. I tried to place it in the `/img` folder and it does not work. – Sami Al-Subhi Jan 08 '18 at 09:31
  • so, when you use `$destination_path = "/../img/";` without error suppression, it doesn't work but you have not error at all? Following the Docs, the only case i see it could happen is if `filename` is invalid, other cases throw errors. Side note: `$name = rand (100,1000);` is not guaranteed to produce a name that doesn't exist already, you should add a check here. – Kaddath Jan 08 '18 at 09:51
  • What kind of OS are you using on your server machine? – b4rt3kk Jan 08 '18 at 09:59
  • I am using Ubuntu 16.04 LTS and PHP 7 – Sami Al-Subhi Jan 08 '18 at 10:00
  • Possible duplicate of [How to upload any type of file to the server using PHP 5?](https://stackoverflow.com/questions/34326754/how-to-upload-any-type-of-file-to-the-server-using-php-5) – Nimesh Patel Jan 08 '18 at 10:20
  • @NimeShPatel It is not. See my answer to my question. – Sami Al-Subhi Jan 08 '18 at 10:22

1 Answers1

0

I am running Ubuntu. The issue was a permission problem. I ran this to fix it:

 sudo chmod 777 /var/www/work_pathname/the_upload_pathname
Sami Al-Subhi
  • 4,406
  • 9
  • 39
  • 66