6

Can somebody pls tell me how to get the filepath using html <input type="file"> in PHP?

Here are my codes:

index.php

<form action="csv_to_database.php" method="get" >
 <input type="file" name="csv_file" />
 <input type="submit" name="upload" value="Upload" />
</form>

and in csv_to_database.php

<?php

 if (isset($_GET['csv_file'])) {

 $row = 1;

  if (($handle = fopen($_GET['csv_file'], "r")) !== FALSE) {
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br /></p>\n";
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
   }
   fclose($handle);
  }

 } 
?>

My problem is, it only works when the csv data is in the same directory as my php files. I think I need to get the file path but I don't know how to do it.

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
Newbie Coder
  • 10,684
  • 19
  • 41
  • 53

3 Answers3

10

You shouldn't just use the $_GET you've got now. Your file is based in $_FILES["csv_file"]["tmp_name"].

Best you review this tutorial, that basically says you need to do something like this:

<?php
if ($_FILES["csv_file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["csv_file"]["error"] . "<br />";
  }
else
  {
  echo "Upload: " . $_FILES["csv_file"]["name"] . "<br />";
  echo "Type: " . $_FILES["csv_file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["csv_file"]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES["csv_file"]["tmp_name"];
  }
?>

And you can go from there. Use move_uploaded_file if you want to move the file from the temp location, also explained in the tutorial :)

Nanne
  • 64,065
  • 16
  • 119
  • 163
3

I think you would gain a lot from taking a look at the following link: POST method uploads.

First of all, you should change your form method to post, and add enctype="multipart/form-data".

Then you can get the temporary file path from $_FILES['csv_file']['tmp_name'].

Kokos
  • 9,051
  • 5
  • 27
  • 44
-1

In your call to fopen, use $_GET['csv_file']['tmp_name'] - this points to the file on the server immediately after upload.

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
David Fells
  • 6,678
  • 1
  • 22
  • 34