Tuesday 23 April 2013

Force file download in PHP

This is code to force a browser to download file.
// Fetch the file info.
    $filePath = '/path/to/file/on/disk.jpg'; // File path here.

    if(file_exists($filePath)) {
        $fileName = basename($filePath); // change file name accroding your requirement here
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }

No comments :

Post a Comment