Viewed   81 times

What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?

I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?



Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename="" . basename($File) . """);
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

Monday, October 3, 2022

Here is a simple function that can compress any file or directory recursively, only needs the zip extension to be loaded.

function Zip($source, $destination)
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;

    $source = str_replace('\', '/', realpath($source));

    if (is_dir($source) === true)
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
            $file = str_replace('\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )

            $file = realpath($file);

            if (is_dir($file) === true)
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            else if (is_file($file) === true)
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
    else if (is_file($source) === true)
        $zip->addFromString(basename($source), file_get_contents($source));

    return $zip->close();

Call it like this:

Zip('/folder/to/compress/', './');
Saturday, December 24, 2022

Send a content-disposition attachment header.

Monday, December 19, 2022

This is pretty easy. All you need to do is provide cURL with a callback to handle data as it comes in.

function onResponseBodyData($ch, $data)
    echo $data;
    return strlen($data);

curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'onResponseBodyData');

Returning the length of data from your callback is important. It signifies how much data you processed. If you return something other than the length of data passed in (such as 0), then the request is aborted.

Now, make sure you don't have output buffering turned on, and configure your server to not buffer the entire response before sending. It will work out of the box on most configurations.

You can find more examples here:

Saturday, December 10, 2022

One thing that you should consider using is serialize and unserialize to encode your cookie data. Just be careful though, from my experience you have to use stripslashes on the cookie value before you unserialize it. This way you can unserialize the data, change the values, reserialize the cookie and send it again. Serialize will make it easier in the future if you want to store more complex data types.

for example:


// This won't work until the next page reload, because $_COOKIE['mycookies']
// Will not be set until the headers are sent    
$cookie_data = unserialize(stripslashes($_COOKIE['mycookies']));
$cookie_data['foo'] = 'bar';
Wednesday, September 28, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :