How to keep using the csv data even after the we lose access to the file?

87 views Asked by At

Sorry if the title is confusing. Let me explain.

I have a function which displays the data in a csv file below.

 <?php
function readCsv($filename, $header=false) {
    $handle = fopen($filename, "r");
    echo "<form method='post' action=''>";

    echo '<table class="table table-hover table-bordered ">';
    if ($header) {
        $csvcontents = fgetcsv($handle);
        echo '<tr>';
        foreach ($csvcontents as $headercolumn) {


            echo "
                <th> <div class='form-check' style='float: right; position: relative'>
                          <input class='form-check-input' type='checkbox' id='check$headercolumn' name='check$headercolumn' />
                 </div>$headercolumn</th>
                 ";

           
    $flag = 0; // show only 5 results from the csv file
    while (($csvcontents = fgetcsv($handle)) && $flag < 5) {
        $flag++;
        echo '<tr>';

        foreach ($csvcontents as $column) {
            echo "<td>$column</td>";
        }
        echo '</tr>';
    }
    echo '</table>';

    echo "<button type='submit' id='submitbut' class='btn'>Submit</button>";
    echo "</form>";



    fclose($handle);
}


 

And the I call it here:

 <form>
    <input type='submit' name='csvsubmit' value='Upload File' class="btn">

</form>


<?php if(isset($_POST['csvsubmit'])){

    readCsv($_FILES['filename']['tmp_name'] , true);

}?>

Which gives me a table like thisenter image description here

Now to the question:

I want to be able to click on each checkbox and just display the columns selected. The problem is, after the submission, I get the error that the path is empty ( I have lost access to the file). How can I go around that? how can I make another submit and not lose access to the csv file?

1

There are 1 answers

2
Rob Ruchte On

You have two general options:

  1. Handle the manipulation of the table in the front end using javascript
  2. Copy the CSV data somewhere on the back end where you can reference it on subsequent requests

If your only requirement is to show and hide columns, #1 is probably the easiest solution to implement. If you need to do more things with the data later on, or come back to it after the user has left the page after the initial submit, you have to go with #2.

If you do decide to keep the CSV for later use, you will need to use the move_uploaded_file function to move the file to a location where you can read it again later, then set some sort of reference in a hidden field in the HTML (just the file name will work) that can then be relayed back to the server on subsequent requests so the server will know which file to read.

You want to move the files to a directory that is outside of the document root of your web server so that the files are not accessible by HTTP request, which could be a serious security risk.