How to get full filepath when uploading files in PHP?

后端 未结 3 1256
花落未央
花落未央 2021-02-10 00:47

I really want to know how am I gonna get the full filepath when I upload a file in PHP?

Here\'s my my problem...

I am importing a csv file in PHP. Uploading a fi

相关标签:
3条回答
  • 2021-02-10 01:30

    The ['name'] refers to the original filename on the users computer. That's no use to you, in particular because it might be empty. (Or it can contain fake values, causing a directory traversal exploit. So, just avoid it.)

    You need to use the ['tmp_name'] which is a server-absolute path like /tmp/upload85728 that can be used for fopen() or move_uploaded_file().

    0 讨论(0)
  • 2021-02-10 01:43

    you need to define a path into your config file or wherever you want to use and then that variable whatever you define, you can use in you project.

    i.e: define('FILE_UPLOADED_PATH','folder1/folder2/so on');
    

    so after the put this code your full filepath would be-

    FILE_UPLOADED_PATH.$_FILES['csv_file']['name'];
    

    you can use above code as example.

    Thanks.

    0 讨论(0)
  • 2021-02-10 01:48

    I was able to successfully imported csv file and stored it in the mysql database.

    Here are the the codes (actually its almost the same as my question with some slight changes with great effect):

    index.php:

    <form action="csv_import.php" method="POST" enctype="multipart/form-data"  >
     <input type="file" name="csv_file" />
     <input type="submit" name="upload" value="Upload" />
    </form> 
    

    csv_import.php:

    <?php
     if ($_FILES['csv_file']['error'] > 0) {
      echo "Error: " . $_FILES['csv_file']['error'] . "<br />"; 
     }else{ 
      if (($handle = fopen($_FILES['csv_file']['tmp_name'], "r")) !== FALSE) {
    
       $dbconn = mysql_connect("localhost", "root", "") or die("Couldn't connect to server!");
       mysql_select_db("csv_test") or die("Couldn't find database!");
    
       $ctr = 1; // used to exclude the CSV header
    
       while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if ($ctr > 1) mysql_query("INSERT INTO ninja_exer (name, village, country) VALUES ('$data[1]', '$data[2]', '$data[3]')");
        else  $ctr++;
       }
       fclose($handle);
      }
     }
    ?>
    
    0 讨论(0)
提交回复
热议问题