Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get full filepath when uploading files in PHP?

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 file isn't a problem but the function used to import csv files which is fgetcsv() requires fopen. fopen is the one giving me a headache because it requires an exact filepath which means that the file should be in the same directory with the php file. What if the user gets a file from a different directory.

Here's my codes:

index.php:

<form action="csv_to_database.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']['name'], "r")) !== FALSE) {

   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

    for ($c=0; $c < count($data) ; $c++) {
     echo $data[$c] . " ";
    }
    echo "<br />";
   }
   fclose($handle);
  }
 }
?>

fopen here can only get the filename which is passed by the variable $_FILES['csv_file']['name']. I was trying to get any functions to get the full filepath for $_FILES in the internet but can't find any.

I am very new to web development so pls be patient. Pls answer as simple as possible... Pls help...

like image 404
Newbie Coder Avatar asked Apr 28 '11 09:04

Newbie Coder


People also ask

How can I get full path of uploaded file in HTML using PHP?

php $dir = dirname(__FILE__); echo "<p>Full path to this dir: " . $dir . "</p>"; echo "<p>Full path to a . htpasswd file in this dir: " .

How do I find the path of a file in PHP?

The is_dir() function in PHP used to check whether the specified file is a directory or not. The name of the file is sent as a parameter to the is_dir() function and it returns True if the file is a directory else it returns False.

How do I find my uploaded files in PHP?

The is_uploaded_file() function in PHP is an inbuilt function which is used to check whether the specified file uploaded via HTTP POST or not. The name of the file is sent as a parameter to the is_uploaded_file() function and it returns True if the file is uploaded via HTTP POST.

What is $_ files [' file Tmp_name ']?

$_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.


1 Answers

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().

like image 65
mario Avatar answered Sep 21 '22 18:09

mario