Create and Download Text File in PHP

please click here for more wordpress cource

To create and download a text file in PHP, you can follow these steps:

  1. Create the content of the text file as a string.
  2. Use the file_put_contents() function to write the content to a file on the server.
  3. Set the appropriate HTTP headers to force a file download.
  4. Output the file contents to the browser.

Here’s an example PHP code that creates and downloads a text file:

<?php
// Create the content of the text file
$content = "This is some sample text.";

// Write the content to a file on the server
$file = 'example.txt';
file_put_contents($file, $content);

// Set the appropriate HTTP headers to force a file download
header('Content-Type: text/plain');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));

// Output the file contents to the browser
readfile($file);
?>

In this example, the file_put_contents() function is used to write the content of the text file to a file named “example.txt” on the server. The header() function is then used to set the appropriate HTTP headers to force a file download. Finally, the readfile() function is used to output the contents of the file to the browser.

Note: The file download functionality will only work if this code is executed on a web server that supports PHP and has the necessary configuration to handle the header() and readfile() functions correctly.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *