Reputation: 496
I'm Importing Data in my Database and I'd like to provide some error/feedback to the user in a text file, but I'm not sure how to approach it. My code is pretty long so I'll put a sample code to write in a file
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
In this case I would want "John Doe" twice in my file and upload to the screen so that the user can download it
Upvotes: 1
Views: 276
Reputation: 7617
You may want to try the Snippet below:
<?php
$fileName = "data-log.txt";
// IF THE FILE DOES NOT EXIST, WRITE TO IT AS YOU OPEN UP A STREAM,
// OTHERWISE, JUST APPEND TO IT...
if(!file_exists($fileName)){
$fileMode = "w";
}else{
$fileMode = "a";
}
// OPEN THE FILE FOR WRITING OR APPENDING...
$fileHandle = fopen($fileName, $fileMode) or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($fileHandle, $txt);
$txt = "Jane Doe\n";
fwrite($fileHandle, $txt);
fclose($fileHandle);
// PUT THE FILE UP FOR DOWNLOAD:
processDownload($fileName);
function processDownload($fileName) {
if($fileName){
if(file_exists($fileName)){
$size = @filesize($fileName);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $fileName);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
readfile($fileName);
exit;
}
}
return FALSE;
}
?>
Upvotes: 0
Reputation: 171
You can use php readfile()
to send a file to the output buffer. You can look at the php docs for an example on how to do this. Readfile()
A sample would look like this
if (file_exists($myfile)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($myfile).'"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . filesize($myfile));
readfile($myfile);
exit;
}
Upvotes: 1