0

What if I have no way of getting the input file:

<input type="file" name="upload" id="upload">

After choosing the file I want to upload, the input field will disappear. Instead, it will display the absolute path:

C:\users\foo\Desktop\file.zip
C:\fakepath\file.zip

Here's the code I used to get the absolute path:

<script>
$('#upload').on('change',function(){

var filename = document.getElementById("filename").innerHTML;

$.ajax({
    type: "POST",
    url: "execs/upload.php",
    data: { filename: filename},
    dataType: "json",
    success: function (data) {
        alert ("Success")
    },

    error: function () {
        alert ("Failed")
    }
  });
})
</script>

Will I still be able to upload it in PHP? Most of what I get online is that I will need $_FILES['filename']['tmp_name']. I don't know how I'll get it if I only have the absolute path.

This is the upload.php file:

<?php

$filename = $_POST["filename"];  //C:\users\foo\Desktop\file.zip
$target_dir = "uploads/";
$target_file = $target_dir . $filename;

if(move_uploaded_file($filename, $target_file)){  // $target_file = uploads/file.zip
echo "yes";
} 
else echo "no";
?>

When I also checked if the file exists ($filename), it says it does NOT.

Any help would be very much appreciated! Thanks a lot!

Mary
  • 169
  • 1
  • 4
  • 13

5 Answers5

0

You should not use $_POST[] for a file input, use $_FILES[] instead.

For more information check this tutorial.

Sayed
  • 1,022
  • 3
  • 12
  • 27
0

Please refer to this post: How to get file name from full path with PHP?

There are two methods:

  1. Using pathinfo.
  2. Using basename.

I prefere pathinfo more.

    <?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');

function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}

filePathParts($xmlFile);
?>

This will return:

/usr/admin/config

test.xml

xml

test

<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
Community
  • 1
  • 1
ashok_p
  • 741
  • 3
  • 8
  • 17
0

Instead of $_POST use $_FILES as

$filename = $_FILES["upload"];
print_r($filename);
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
0
    <?php
            $uploaddir = "/www/uploads/";
           $uploadfile = $uploaddir . basename($_FILES['upload']['name']);

   echo '<pre>';
   if (move_uploaded_file($_FILES['upload']['tmp_name'], $uploadfile)) {
         echo "Success.\n";
   } else {
         echo "Failure.\n";
   }

  echo 'Here is some more debugging info:';
  print_r($_FILES);
  print "</pre>";
?>
vishuB
  • 4,173
  • 5
  • 31
  • 49
-2

You have $filename = $_POST["filename"]; but change that to:

$filename = $_POST["upload"];

Since you have:

<input type="file" name="upload" id="upload">

So: name="upload"
Cris Kolkman
  • 165
  • 2
  • 10