PHP and writing to the the user's HDD, possible ?
Okay, with writing to the user's HDD prohibited, I implemented a force download instead:
In brief:
1) Create folder so hold generated text files
2) Write files to said folder
3) Zip files up
4) Force download of zipped file
In detail:
The above steps had to be done at the end of the PHP code, after the text for the files is generated and placed into an array (contents of array used to create text files on the system).
The code is placed before the ?> tag, which marks the end of the PHP code
1) Create folder to hold generated text files
Code: Select all
mkdir(“filesFolder”); // I actually use the user's login ID for the folder name
2) Write files to said folder
Code: Select all
// output result
$fileName = $folderName . "/file";
for ($i=0; $i < $totalNumberTextFiles; $i++)
{
$ fileName .= $i; // e.g. fileName becomes “filesFolder/file01”
file_put_contents($fileName,$textDocuments[$i]); // store 1 text file
$ fileName = $folderName . "/file"; // reset file name
}
3) Zip files up
Code: Select all
// zip folder up
exec("zip -r text_files.zip " . $folderName . "/");
4) Force download of zipped file
Code: Select all
// force file download
$file = "text_files.zip";
// Set headers
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file");
header("Content-Transfer-Encoding: binary");
@readfile($file);
5) Tidy up – delete folder
et voilà, job done
Obviously you cannot say where the file should be downloaded to, but at least it is now going to the user's own computer's HDD.
POSSIBLE ERRORS:
I had a problem with it reporting that the Headers had already been sent.
“Cannot modify header information - headers already sent by.... “
Solved it by removing all the echo statements I had put in during testing.
Basically, when using headers you cannot have echo statements before the Header statements in the PHP code. Also, you cannot have blank spaces before the <?php or after the ?>