0

I have the following function that exports the data from an array to a csv file.

function exportcsv($dataArray , $fileName){


    $file = fopen("$fileName.csv","w");

    fputcsv($file , $dataArray['checkedArr']); // write the columns


    foreach ($dataArray['selectedData'] as $data){ // write the data
        fputcsv($file , $data);
    }

    fclose($file);


}

However this file is being created in the same folder as the page I'm using it in. How can I export this file to another folder?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Rey
  • 41
  • 5
  • Really simply: `fopen("Some/Other/Folder/name/$fileName.csv","w");` – RiggsFolly Jul 07 '21 at 13:16
  • Also please dont SPAM Tags, this is nothing to do with javascript or html. Thay are designed to gather a relevant audience, if you add irrelevant tags you just waste peoples time – RiggsFolly Jul 07 '21 at 13:20
  • @RiggsFolly Thank you. And you are right, my apologies – Rey Jul 07 '21 at 13:59

1 Answers1

1

The filename in fopen can contain a path too. So you can try something like this:

function exportcsv($dataArray, $path, $fileName){


    $file = fopen("$path/$fileName.csv","w");

    fputcsv($file , $dataArray['checkedArr']); // write the columns


    foreach ($dataArray['selectedData'] as $data){ // write the data
        fputcsv($file , $data);
    }

    fclose($file);


}

Keep in mind that the code above is just example code. If you are taking in the $path variable from the user this could lead to very bad results.

tantalum
  • 2,354
  • 1
  • 15
  • 22
  • Thank you for your answer. In this case, I'm not getting the path from the user, but I'm just curious, how does it lead to bad results? – Rey Jul 07 '21 at 14:02
  • @Rey Since the user controls the path, the can create a special string that will cause your function to over write any file they want. – tantalum Jul 07 '21 at 18:47