• 0

Using header() to force download not working in Chrome or Firefox


Question

I have created an mp3 downloader script which forces downloads of MP3s that are located outside of the web root. I've received a few support requests saying it's not working.. I originally only tested it in Safari and it worked fine, so I tested it in Chrome and Firefox and can confirm it returns a 404 error in both of those browsers.

In Chrome console it shows: net::ERR_INVALID_RESPONSE

download.php:

header("Content-Description: File Transfer");
header("Content-Type: {$mime}");
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download"); 
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename={$filename}");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($file));
while(ob_get_level()) ob_end_clean();
flush();
readfile($file);
exit;

 

I have checked all paths and variables.. everything is set, exists and readable.

If i remove application/force-download and application-download it loads the in browser mp3 player but returns a 404... so it looks like it can't find the file outside of web root - does Chrome/Firefox not allow that?

It is definitely working in Safari

Any ideas?

4 answers to this question

Recommended Posts

  • 0

Check your Inspect Element tool on Chrome and see if it's blocking it client sided, I ran into issues with loading javascript files / modifying css through an iframe for security reasons. If you're on a windows device using safari, you're using a very outdated version (merely an assumption you're on windows) which may not have included a patch for cross-site anything.

I know that you get into a really grey area when you start using cross-site downloads without the appropriate allow-content headers on the receiving and requesting servers.

  • 0

A few of these headers are meaningless outside of email (Content-Description and Content-Transfer-Encoding), and overwriting the content-type multiple times won't help much either (You ideally want to either use the original mime-type, or application/octet-stream. I have no idea what uses "download" or "force-download").

It returning a 404 is the more likely problem, PHP is actually using the $filename and $mime in the headers right? (Been ages since I've used PHP) It's also odd that you're just downing normal string concatenation for the filesize, but not for other headers.

  • 0
  On 18/08/2015 at 06:00, The_Decryptor said:

A few of these headers are meaningless outside of email (Content-Description and Content-Transfer-Encoding), and overwriting the content-type multiple times won't help much either (You ideally want to either use the original mime-type, or application/octet-stream. I have no idea what uses "download" or "force-download").

It returning a 404 is the more likely problem, PHP is actually using the $filename and $mime in the headers right? (Been ages since I've used PHP) It's also odd that you're just downing normal string concatenation for the filesize, but not for other headers.

Thanks for your input, i removed the 'meaningless' headers and it still works in Safari so i'll leave those out. It didn't fix the chrome issue though.

  • 0

This has always worked for me:

  • $file = "filename.ext";
  •  
  • // Quick check to verify that the file exists
  • if( !file_exists($file) ) die("File not found");
  •  
  • // Force the download
  • header("Content-Disposition: attachment; filename="" . basename($file) . """);
  • header("Content-Length: " . filesize($file));
  • header("Content-Type: application/octet-stream;");
  • readfile($file);

 

This topic is now closed to further replies.
  • Posts

    • uBO works best in gecko based browsers. If you don't believe me, believe the developer of uBO:) He is a firefox user for a reason:) https://github.com/gorhill/uBl...rigin-works-best-on-Firefox
    • Kdenlive 25.04.2 by Razvan Serea Kdenlive is an acronym for KDE Non-Linear Video Editor. It works on GNU/Linux, Windows and BSD. Through the MLT framework, Kdenlive integrates many plugin effects for video and sound processing or creation. Furthermore Kdenlive brings a powerful titling tool, a DVD authoring (menus) solution, and can then be used as a complete studio for video creation. Kdenlive supports all of the formats supported by FFmpeg or libav (such as QuickTime, AVI, WMV, MPEG, and Flash Video, among others), and also supports 4:3 and 16:9 aspect ratios for both PAL, NTSC and various HD standards, including HDV and AVCHD. Video can also be exported to DV devices, or written to a DVD with chapters and a simple menu. Video editing features: Multi-track editing with a timeline and supports an unlimited number of video and audio tracks. A built-in title editor and tools to create, move, crop and delete video clips, audio clips, text clips and image clips. Ability to add custom effects and transitions. A wide range of effects and transitions. Audio signal processing capabilities include normalization, phase and pitch shifting, limiting, volume adjustment, reverb and equalization filters as well as others. Visual effects include options for masking, blue-screen, distortions, rotations, colour tools, blurring, obscuring and others. Configurable keyboard shortcuts and interface layouts. Rendering is done using a separate non-blocking process so it can be stopped, paused and restarted. Kdenlive also provides a script called the Kdenlive Builder Wizard (KBW) that compiles the latest developer version of the software and its main dependencies from source, to allow users to try to test new features and report problems on the bug tracker. Project files are stored in XML format. An archiving feature allows exporting a project among all assets into a single folder or compressed archive. Built-in audio mixer Highlights from the Kdenlive 25.04.2 update: Remember title editor window width Fix audio thumbnails have an offset in long files Fix OTIO import path on Windows Better feedback when auto mask fails Fix OTIO export tracks order and ensure .otio file extension is correctly added Full Changelog Fix moving subtitle with grab. Fix empty gradient in config causes crash. Snapcraft: Give more permissions for microphone access. Backport missing effects xml. Fix quick markers not taking clip crop into account in timeline. Fix marker dialog not allowing to add marker if only 1 category exists. Fix merge error causing freeze on exit. Fix crash in HistogramGenerator when running on a white color clip. Fix Whisper model directory not being created if asked to do so. Fix canceling quit on rendering leaves kdenlive in unstable state. Only clear undo stack when we delete a timeline sequence, not a standard bin clip. Fix misalignment of monitor tools CCBUG: 498337 CCBUG:461219. Fix OTIO path issue on import, related to #1998. Fix bin clip effects disappear after disabling a timeline clip. Fix keyframe in monitor not correctly reported on clip selection. Fix monitor scene not correcty activated on clip selection. Fix small error causing offset in long audio thumbnails. Fix guides list buttons not working on app opening. Fix built-in effects disabled state changes on cut. Fix render widget target file can have no extension or incorrect path. SAM2: show message and full log if the python script crashes, try to auto reinstall if the venv python exe is missing. Save and restore title editor window width. Download: Kdenlive 25.04.2 | 116.0 MB (Open Source) Download: Standalone Executable Links: Kdenlive Home page | Other Operating Systems Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I use Edge on my Mac. Edge is lightning fast and does everything. Never had an issue with it. It alsoi allows the use of the original uBlock Origin extension, which Chrome does not allow anymore. I hate ads.
    • AIMP 5.40 Build 2682 by Razvan Serea AIMP is a powerful audio player that allows you to listen to your favorite music with an outstanding sound quality. Its appearance resembles that of another classical audio player (Winamp). The program includes a 20-band equalizer, a visualization window to display rhythmic visual effects and a playlist editor to organize your audio files. A nice fading effect makes your list of songs look like an endless music loop and a handy volume normalizing feature avoids drastic volume changes between tracks. Also, the players main functions can be conveniently controlled by global hotkeys. Besides playing music, AIMP features three extra utilities which also enable you to record any sound on your computer, convert audio files from one format to another and view or edit tags. AIMP is based on the well-known audio engine BASS, so its easy to connect new plug-ins (from the plug-in library included in the program) and expand the players functionality. Main Features and Functions: Multi-Format Playback: Supports numerous audio formats, including CDA, AAC, AC3, APE, DTS, FLAC, IT, MIDI, MO3, MOD, M4A, M4B, MP1, MP2, MP3, MPC, MTM, OFR, OGG, OPUS, RMI, S3M, SPX, TAK, TTA, UMX, WAV, WMA, WV, XM, DSF, DFF, MKA, AA3, AT3, OMA, WebM, MDZ, ITZ, S3Z, XMZ, AIFF, and MPEG-DASH (YouTube). CUE Sheet Support: Enables the use of CUE sheets for managing audio tracks. Output Support: Compatible with DirectSound, ASIO, WASAPI, and WASAPI Exclusive output methods. 32-Bit Audio Processing: Utilizes 32-bit audio processing for optimal sound quality. Internet Radio: Allows listening to internet radio stations in OGG, WAV, MP3, AAC, and AAC+ formats, with the capability to capture streams in various formats. Bookmarks and Playback Queue: Facilitates creating bookmarks and managing a playback queue. Rating and Auto-Marks: Collects statistics on track listening and automatically calculates ratings and marks for listened tracks. Plugin Support: Allows the addition of new utilities or extensions to existing features through plugins. Built-in Scrobbler: Supports Last.fm, Libre.fm, and ListenBrainz services for scrobbling. Cloud Integration: Supports OneDrive, Google Drive, DropBox, Облако@mail.ru, Яндекс.Диск, and custom WebDAV clouds. Podcasts: Offers podcast support for subscribing and listening. Hotkeys: Allows configuration of local and global hotkeys. Multi-User Mode Support: Supports multiple users working on one computer. Multi-Language Interface: Provides a multi-language interface. 4K and High DPI Support: Supports scale factors of 125%, 150%, 175%, and 200% for high-resolution displays. Flexible Program Options: Offers customizable program settings. Flexible UI: Charm UI: A modern flat-style skin with 4K and High DPI support. Bliss 4K: A skin-transformer from AIMP4 included in the installation package. Pandemic: The classic skin from AIMP3 included in the installation package. User Skins: Access to a catalog of user-created skins. Sound Effects: 20-Band Equalizer and Built-in Sound Effects: Includes Reverb, Flanger, Chorus, Pitch, Tempo, Echo, Speed, Bass, Enhancer, and Voice Remover effects with flexible settings. Volume Normalization: Features peak-based normalization and Replay Gain, along with logarithmic and loudness-compensated volume control. Mixing Options: Offers Fade In/Fade Out, cross-mixing, and pause between tracks. Silence Remover: Removes silence from tracks for a seamless listening experience. Music Library: Music Library: Organizes music files, allows setting marks for listened tracks, and keeps playback statistics. Smart Playlist: Creates playlists based on content from the Music Library database, with filtering and grouping capabilities. Playlists: Multiple Playlists: Supports working with multiple playlists simultaneously. Powerful View Settings: Allows data display customization, track grouping, and separate settings for each playlist. Content Protection: Provides the ability to block content from changes. File Search: Enables searching files across all opened playlists. AIMP 5.40 Build 2682 changelog: Audio converter: support for relative paths Plugins: analog meter - installing skins using general approach to install addons Sound engine: resampler algorithm has been improved Player: AB part repeat - an ability to change milliseconds via dialog Skin engine: compatibility with the Start11 app Skin engine: memory consumption during skin loading has been reduced Fixed: Tags editor - data in tags with multiple values ​​​​may be duplicated in certain cases Fixed: tag editor - ID3v2.4 - multiple genre values ​​cannot be loaded Fixed: skin engine - minor issues has been fixed Fixed: issues from incoming crash-reports Download: AIMP 64-bit | AIMP 32-bit ~20.0 MB (Freeware) View: AIMP Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Can you point out where his walkthrough of Mozilla's finances are lies?
  • Recent Achievements

    • Reacting Well
      Alan- earned a badge
      Reacting Well
    • Week One Done
      IAMFLUXX earned a badge
      Week One Done
    • One Month Later
      Æhund earned a badge
      One Month Later
    • One Month Later
      CoolRaoul earned a badge
      One Month Later
    • First Post
      Kurotama earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      494
    2. 2
      ATLien_0
      267
    3. 3
      +FloatingFatMan
      223
    4. 4
      +Edouard
      199
    5. 5
      snowy owl
      141
  • Tell a friend

    Love Neowin? Tell a friend!