Skip to content
PHP Logo

How can PHP be used to directly download a string without saving it as a file on the server first?

To directly download a string without saving it as a file on the server first, you can use PHP's output buffering capabilities along with appropriate headers to force the browser to download the string as a file. By setting the correct content type and headers, you can prompt the browser to download the string as a file without the need to save it on the server.

php
<?php
// String to be downloaded
$string = "Hello, World!";

// Set appropriate headers for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="downloaded_string.txt"');

// Output the string directly to the browser
echo $string;