Search code examples
phpfile-permissionsforce-download

Set Permission on forced download file


I have to force download an excel file. File is being download perfectly as I want. But problem is that when I'm going to change and save the content of the file, I got error showing like I have not access to change file. So, I have to set permissions on file while downloading it. But I don't know how. If anyone can answer, then it will be appreciated. Here is my code which work perfectly as downloading file.

$filename = 'myfile.xlsx';
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";     //$header and $data are the array contains data with '\t' (tabular form data).

As I changed my code o this. But still there is problem. Problem is that this code sets permission to only file created on server side, not to file downloaded on client side. Here is updated code.

$filename = 'myfile.xlsx';
$fp = fopen('/var/www/html/cakephp-3.0/webroot/downloads/' . $filename, 'w');
fwrite($fp, "$header\n$data");
fclose($fp);
chmod('/var/www/html/cakephp-3.0/webroot/downloads/' . $filename, 0777);

// Generate Excel File
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
readfile('/var/www/html/cakephp-3.0/webroot/downloads/' . $filename);

Solution

  • Solved. As problem was client side, file was being saved in some folder in which all file will be read-only by default. So, as I changed download folder location, it works perfectly now. So code was already absolutely correct.