25

I have a form(HTML, PHP) that lets the end user upload a file to update the database(MySQL) with the records in the uploaded file(specifically .csv). However, in the phpscript, I can only get the filename and not the complete path of the file specificed. fopen() fails due to this reason. Can anyone please let me know how I can work on finding the complete path?

HTML Code:

<html>
<head>
</head>
<body>
<form method="POST" action="upload.php" enctype="multipart/form-data">
    <p>File to upload : <input type ="file" name = "UploadFileName"></p><br />
    <input type = "submit" name = "Submit" value = "Press THIS to upload">
</form>
</body>
</html>

PHP Script:

<?php
   .....
......
   $handle = fopen($_FILES["UploadFileName"]["name"], "r"); # fopen(test.csv) [function.fopen]: failed to open stream: No such file or directory
?>
name_masked
  • 9,544
  • 41
  • 118
  • 172
  • this is helpful good question. – Rana Aalamgeer Oct 05 '16 at 11:26
  • old question, still, I think such comment is missing here: `$_FILES["UploadFileName"]["name"]` does not exist. `$_FILES["UploadFileName"]["tmp_name"]` does and `move_uploaded_file` is meant to move from tmp name to whatever location you wish. – Jiří Oct 19 '22 at 13:41
  • however, sometimes you NEED the complete path of the uploaded file (client side), for example, some file formats use directory hierarchy - this will be available as of 8.1 – Jiří Oct 19 '22 at 13:43

5 Answers5

37

name refers to the filename on the client-side. To get the filename (including the full path) on the server-side, you need to use tmp_name:

$handle = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
netcoder
  • 66,435
  • 19
  • 125
  • 142
4
$target='uploads/'.basename($_FILES['UploadFileName']['name']);

if(move_uploaded_file($_FILES['UploadFileName']['tmp_name'],$target)) {

     //Insert into your db

     $fp = fopen($target, "r");
}
ShivarajRH
  • 902
  • 12
  • 24
4

I wrote like this:

$filePath = realpath($_FILES["file"]["tmp_name"]);

This gave me the full path to the uploaded file in PHP. If you find 0 bytes problem in file download, just modify this content-lenght line like this

header("Content-Length: ".filesize($filePath));

Where $filePath should be absolute path to file not just file handle.

webblover
  • 1,196
  • 2
  • 12
  • 30
2

Use the following code,

$handle = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');
Vijin Paulraj
  • 4,469
  • 5
  • 39
  • 54
1

I use like this...

<?php
$NameOriginal = $_FILES["UploadFileName"]['name'];
$Typo_Image = $_FILES["UploadFileName"]['type'];
$name_Temp = $_FILES["UploadFileName"]['tmp_name']; 
?>