What's new

PHP Pa help po can download any file type

Phc_Kite

Forum Veteran
Joined
Aug 31, 2018
Posts
1,114
Solutions
1
Reaction
5,657
Points
969
pa help po mga sir about kung pano coding ng pwd a download any file type and then any device type

ito po kasi ginawa po and then corrupted sya pag bigfile na ang denadownload and then sa ibang device namn halimawa mp3 ok namn sa desktop pero pag phone na ang nag download corrupted na sya

ito po ung code ko

if (!$DEVICE) {
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.android.package-archive');
header("Content-length: " . filesize($file));
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
return true;
}else{
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="' . basename($file) .'"');
readfile($file);
}
 
Based on the code you provided, here are some modifications you can make to ensure that files can be downloaded correctly and are not corrupted:

1. Check the file exists: Before initiating the download, make sure to check that the file exists on the server. If the file doesn't exist, you can display an error message or redirect the user to an appropriate page.

2. Set appropriate headers: Set the appropriate headers based on the file type. You can use the mime_content_type() function to get the file's MIME type and set the Content-Type header accordingly. This will ensure that the browser and client device interpret the file correctly. For example:

PHP:
$file = 'path/to/file'; // Replace with the actual file path
if (file_exists($file)) {
    $fileSize = filesize($file);
    $fileType = mime_content_type($file);
    
    header('Content-Description: File Transfer');
    header('Content-Type: '.$fileType);
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . $fileSize);
    
    readfile($file);
    exit;
} else {
    // File not found, display error message or redirect
    echo 'File not found.';
}

3. Handle larger file downloads: For larger files, you may need to adjust some server configurations to allow longer execution times and larger file uploads. You can try increasing the max_execution_time and upload_max_filesize settings in your PHP configuration file (php.ini). Additionally, you can use the set_time_limit() function to set the maximum execution time for the script.

These modifications should help ensure that the files can be downloaded correctly on different devices without getting corrupted.
 
Back
Top