fput csv output file recommended path for sensitive files - php

I have a query that returns an array which is then processed by this function to ultimately write the output to a csv file. My question is about the path of the output file, it should not be accessible via the web root hence the idea to have the path as /tmp/ instead? Or should I create a new folder specifically for the uploads outside of the web root? So basically I just want to make sure that no one browsing our website, which is pretty much locked down anyway to specific ip's can access the csv files generated by this function. P
$date = date("Y-m-d H:i:s");
$file = $date . ".csv";
function array_to_csv_download($array, $filename, $delimiter = ",")
{
header("Content-Type: application/csv");
header('Content-Disposition: attachment; filename="' . $filename . '";');
$u = "/tmp/" . $filename;
// open the "output" stream
$f = fopen($u, "a");
$csv = array_map("str_getcsv", file($u));
if (isset($csv[0])) {
//do nothing
} else {
//header
$fields = ["Name", "Contact Number"];
fputcsv($f, $fields, $delimiter);
}
//content
foreach ($array as $line) {
//foreach ($array as $header => $line)
fputcsv($f, $line, $delimiter);
}
}
array_to_csv_download($customer_id_result, $file);
P.S. Hope I can post this type of question here, if not please advise on which site part of the group

Related

How to export multiple csv files at once

This exports one file with 2 rows in it. How can export 2 files each with one row in it?
<?php
$list = array (
array("Peter", "Griffin" ,"Oslo", "Norway"),
array("Glenn", "Quagmire", "Oslo", "Norway")
);
$file = fopen("contacts.csv","w");
foreach ($list as $line) {
fputcsv($file, $line);
}
fclose($file);
?>
I tried this:
$list = array (
array("Peter", "Griffin" ,"Oslo", "Norway"),
array("Glenn", "Quagmire", "Oslo", "Norway")
);
$file = fopen('php://output', 'w');
$i = 1;
foreach ($list as $line) {
header('Content-Disposition: attachment; filename="' . $i . 'wp.csv"');
fputcsv($file, $line);
fclose($file);
$i++;
}
But it only downloads one file. At least it only has the one row in it though.
I found this example. Even though it creates 2 separate csv files, the data is identical in each file instead of each file containing an individual record.
// some data to be used in the csv files
$headers = array('id', 'name', 'age', 'species');
$records = array(
array('1', 'gise', '4', 'cat'),
array('2', 'hek2mgl', '36', 'human')
);
// create your zip file
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create 3 csv files
for ($i = 0; $i < 3; $i++) {
// create a temporary file
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
// write the data to csv
fputcsv($fd, $headers);
foreach($records as $record) {
fputcsv($fd, $record);
}
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('file-'.$i.'.csv', stream_get_contents($fd) );
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
You can only put one "file" into an HTTP response.
If you want to generate multiple CSV files then you'll need to get more exotic. You could generate a HTML document of links to URLs that each generate a CSV file, or you could generate a zip file containing the CSV files.
Just make a new File and use it like this
$file2 = fopen("contacts2.csv", "w");
fputcsv($file2, $list[1]);
You always write in the same file here, because you are refering to $file
fputcsv($file, $list[1]);

Delete the first line of the file

Im having a problem of exporting my csv. Yes it can export but when it exported the colmun name is included. How can i remove the first row (column name) after i exported?
Tried looking for other solution yet it doesnt fit on my program
<?php
//include database configuration file
include 'config2.php';
//get records from database
$query = $db->query("SELECT * FROM maternalproblem ");
if($query->num_rows > 0){
$delimiter = ",";
$filename = "maternalproblem" . date('Y-m-d') . ".csv";
//create a file pointer
$f = fopen('php://memory', 'w');
//set column headers
$fields = array('MPID', 'district_id', 'barangay_id', 'PID', 'tuberculosis', 'sakit','diyabetes','hika','bisyo');
fputcsv($f, $fields, $delimiter);
//output each row of the data, format =line as csv and write to file pointer
while($row = $query->fetch_assoc()){
$lineData = array($row['MPID'], $row['district_id'], $row['barangay_id'], $row['PID'], $row['tuberculosis'],$row['sakit'],$row['diyabetes'],$row['hika'],$row['bisyo']);
df.to_csv($filename , header=False);
fputcsv($f, $lineData, $delimiter);
}
//move back to beginning of file
fseek($f, 0);
//set headers to download file rather than displayed
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
exit;
?>
I just need to export the data and not with the column name. Thank you
It would probably be simpler to just not put the column titles out into the file
So remove these lines
//set column headers
$fields = array('MPID', 'district_id', 'barangay_id', 'PID', 'tuberculosis', 'sakit','diyabetes','hika','bisyo');
fputcsv($f, $fields, $delimiter);

Saving CSV file instead of downloading

So I have this code to generate a CSV file from mysql database. But however, it downloads the code instead of saving it to the directory for further use (need to send that file via phpmailer).
What changes should I do to make it save the file to the directory.
$array = array();
if(file_exists('records_monthly.csv'))
{
unlink('records_monthly.csv');
}
# Headers
$array[] = array("Serial Number","Donation Type", "Amount", "Status", "Date", "Orderref", "DIN");
$serial=1;
try
{
$s = $conn->query("SELECT c.firstname AS firstname, c.lastname as lastname, c.address AS address, c.city AS city, c.postalnumber AS postalnumber, c.email AS cemail, d.donation_type as donation_type, d.donation_amount as donation_amount, d.orderref as orderref, d.status as status, d.donation_on AS donation_on, d.din as din from customers c, donations d where c.email = d.donator");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
while($donations = $s->fetch(PDO::FETCH_OBJ))
{
if($donations->status == 0)
{
$array[] = array($serial++,$donations->donation_type,$donations->donation_amount,"Failed",$donations->donation_on,$donations->orderref,$donations->din);
}
else
{
$array[] = array($serial++,$donations->donation_type,$donations->donation_amount,"Success",$donations->donation_on,$donations->orderref,$donations->din);
}
}
array_to_csv_download($array,"records_monthly.csv",",");
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// rewind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
Write directly to the named file rather than to php://memory and don't send headers and output to the browser
function array_to_csv_without_download($array, $filename = "export.csv", $delimiter=";") {
$f = fopen($filename, 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
fclose($f);
}

How to create and download a csv file from php script?

I am a novice programmer and I searched a lot about my question but couldn't find a helpful solution or tutorial about this.
My goal is I have a PHP array and the array elements are showing in a list on the page.
I want to add an option, so that if a user wants, he/she can create a CSV file with array elements and download it.
I don't know how to do this. I have searched a lot too. But yet to find any helpful resource.
Please provide me some tutorial or solution or advice to implement it by myself. As I'm a novice please provide easy to implement solutions.
My array looks like:
Array
(
[0] => Array
(
[fs_id] => 4c524d8abfc6ef3b201f489c
[name] => restaurant
[lat] => 40.702692
[lng] => -74.012869
[address] => new york
[postalCode] =>
[city] => NEW YORK
[state] => ny
[business_type] => BBQ Joint
[url] =>
)
)
You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:
$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
fputcsv($f, $line);
}
To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):
header('Content-Disposition: attachment; filename="filename.csv";');
Putting it all together:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
// open raw memory as file so no temp files needed, you might run out of memory though
$f = fopen('php://memory', 'w');
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line, $delimiter);
}
// reset the file pointer to the start of the file
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: text/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachment; filename="'.$filename.'";');
// make php send the generated csv lines to the browser
fpassthru($f);
}
And you can use it like this:
array_to_csv_download(array(
array(1,2,3,4), // this array is going to be the first row
array(1,2,3,4)), // this array is going to be the second row
"numbers.csv"
);
Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
// open the "output" stream
// see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
$f = fopen('php://output', 'w');
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
I don't have enough reputation to reply to #complex857 solution. It works great, but I had to add ; at the end of the Content-Disposition header. Without it the browser adds two dashes at the end of the filename (e.g. instead of "export.csv" the file gets saved as "export.csv--"). Probably it tries to sanitize \r\n at the end of the header line.
Correct line should look like this:
header('Content-Disposition: attachment;filename="'.$filename.'";');
In case when CSV has UTF-8 chars in it, you have to change the encoding to UTF-8 by changing the Content-Type line:
header('Content-Type: application/csv; charset=UTF-8');
Also, I find it more elegant to use rewind() instead of fseek():
rewind($f);
Thanks for your solution!
Try...
csv download.
<?php
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
$data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
echo $data; exit();
?>
That is the function that I used for my project, and it works as expected.
function array_csv_download( $array, $filename = "export.csv", $delimiter=";" )
{
header( 'Content-Type: application/csv' );
header( 'Content-Disposition: attachment; filename="' . $filename . '";' );
// clean output buffer
ob_end_clean();
$handle = fopen( 'php://output', 'w' );
// use keys as column titles
fputcsv( $handle, array_keys( $array['0'] ), $delimiter );
foreach ( $array as $value ) {
fputcsv( $handle, $value, $delimiter );
}
fclose( $handle );
// flush buffer
ob_flush();
// use exit to get rid of unexpected output afterward
exit();
}
Use the below code to convert a php array to CSV
<?php
$ROW=db_export_data();//Will return a php array
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=test.csv");
$fp = fopen('php://output', 'w');
foreach ($ROW as $row) {
fputcsv($fp, $row);
}
fclose($fp);
If you're array structure will always be multi-dimensional in that exact fashion, then we can iterate through the elements like such:
$fh = fopen('somefile.csv', 'w') or die('Cannot open the file');
for( $i=0; $i<count($arr); $i++ ){
$str = implode( ',', $arr[$i] );
fwrite( $fh, $str );
fwrite( $fh, "\n" );
}
fclose($fh);
That's one way to do it ... you could do it manually but this way is quicker and easier to understand and read.
Then you would manage your headers something what complex857 is doing to spit out the file. You could then delete the file using unlink() if you no longer needed it, or you could leave it on the server if you wished.
Update for UTF-8 Encoding
Updating #complex857 's answer
function array_to_csv_download($array, $filename = "export.csv", $delimiter=",") {
header('Content-Disposition: attachment; filename="'.$filename.'";');
header('Content-Type: application/csv; charset=UTF-8');
// open the "output" stream
$f = fopen('php://output', 'w');
// Write utf-8 bom to the file
fputs($f, chr(0xEF) . chr(0xBB) . chr(0xBF));
foreach ($array as $line) {
fputcsv($f, $line, $delimiter);
}
}
May be a bit ugly code but it works!
This function can generate a downloadable CSV file, you can set up the name and the delimiter without tricky functions (UTF-8 encoding in header function).
/**
* Array2CSVDownload
*
*/
function Array2CSVDownload($array, $filename = "export.csv", $delimiter=";") {
// force object to be array, sorry i was working with object items
$keys = array_keys( (array) $array[0] );
// use keys as column titles
$data = [];
array_push($data, implode($delimiter, $keys));
// working with items
foreach ($array as $item) {
$values = array_values((array) $item);
array_push($data, implode($delimiter, $values));
}
// flush buffer
ob_flush();
// mixing items
$csvData = join("\n", $data);
//setup headers to download the file
header('Content-Disposition: attachment; filename="'.$filename.'";');
//setup utf8 encoding
header('Content-Type: application/csv; charset=UTF-8');
// showing the results
die($csvData);
}

How to rename .txt files before being added to zip using ZipArchive()?

I am using ZipArchive() to zip a bunch of .txt files together. Can someone please give me an example how to remove the ID from the beginning of all .txt files before placing them in the zip?
For example:
144-apples.txt
2-oranges.txt
25555-bananas.txt
will be:
apples.txt
oranges.txt
bananas.txt
in the zip.
$name = str_replace(TXT_FILE_DIRECTORY . $group . '/', '', $file);
$zip->addFile($file, $name);
Something like this should work:
<?php
//Your $files array creation logic here
foreach ($files as $file) {
$fileName = preg_replace("/^\d+\-/", "", str_replace(TXT_FILE_DIRECTORY . $group . '/', '', $file));
$zip->addFile($file, $fileName);
}
?>
maybe you can serve the following code:
$this->zipfile->add_dir(FCPATH."files/");
for($u=$ini;$u<=$do;$u++){
$this->zipfile->add_file(implode("",file(FCPATH."files/batchsql_".$u.".txt")), FCPATH."files/batchsql_".$u.".txt");
}
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=zipfile.zip");
echo $this->zipfile->file();

Categories