Php File Download Example

Posted on by admin

I’ve seen many download scripts written in PHP, from simple one-liners to dedicated classes. If you need to restrict access to a file, you should generate. This page explains how to use PHP to create CSV files, and how to ensure that your visitor’s browser offers to download the file instead of displaying it. The code The following code assumes that the data to be exported are stored in a MySQL database, but it can easily be modified to work with other data sources, and hence serves as a. Is it possible to generate a text file using text from a database and then make that file available for download? I have a client that wants to. If you are trying to download multiple files at the same time and downloading the files one by one, then there is a better option to create a zip file, add the downloading files in the zip and download the zip file. Using PHP, this is very easy. PHP ZipArchive() class provides all functionality to. Today i am sharing how to create a zip file of multiple files using PHP and download that zip file on click. For this purpose i will need a folder where all files are available which can be selected and downloaded.

I have a PHP app that creates a CSV file which is forced to download using headers. Here's the relevant part of the code:

What I'd like to do is redirect users to a new page after the file is built and the download prompt is sent. Just adding header('Location: /newpage') to the end didn't work, expectedly, so I'm not sure how to rig this up.

  1. If you still get strange results when downloading (especially in IE), make sure that the PHP output compression is disabled, as well as any server compression (sometimes the server inadvertently applies compression on the output produced by the PHP script). Handling large file sizes. Readfile is a simple way to ouput files files.
  2. Generate a waveform. You can generate a waveform of an audio file using the FFMpeg Media Audio::waveform method. This code returns a FFMpeg Media Waveform instance. You can optionally pass dimensions as the first two arguments and an array of hex string colors for ffmpeg to use for the waveform, see dedicated documentation below for more information.
EvanEvan
1,4736 gold badges23 silver badges34 bronze badges

MP3 is a lossy audio file format, which was first released by the Moving Picture Experts Group in 1993. Below you will find a selection of sample.mp3 audio files for you to download. On the right there are some details about the file such as its size so you can best decide which one will fit your needs. Downloading Files with PHP. Normally, you don't necessarily need to use any server side scripting language like PHP to download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click on the link, browser will. I found for this excellent guide: How to serve big files through PHP. Especially useful is the lighttpd trick - If your PHP happens to run under lighhtpd, script only needs to set 'X-Sendfile' header, and lighttpd will read and send the file for you (and it well knows how to send files).

11 Answers

I don't think this can be done - although I am not 100% sure.

The common thing (e.g. in popular download sites) is the reverse: first you go to the after page and then the download starts.

So redirect your users to the final page that (among other things) says:

Your download should start automatically. If not click [a href='create_csv.php']here[/a].

As about initiating the download (e.g. automatically calling create_csv.php) you have many options:

  • HTML: [meta http-equiv='refresh']
  • Javascript: location.href = 'http://site/create_csv.php';
  • iframe: [iframe src='create_csv.php'][/iframe]
tilz0R
5,7591 gold badge15 silver badges33 bronze badges
daremondaremon
4,4692 gold badges23 silver badges27 bronze badges

very easy to do in the case it is really needed.

But you will need to have a bit work in JavaScript and cookies:

in PHP you should add setting up a cookie

Php Generate Csv File

then on the page where you call the download you should track with JS (e.g. once per second) if there is coming cookie like that (there is used plugin jQuery cookie here):

Now if the file starts to be downoaded JS recognizes it and redirects to the page needed after cookie is deleted.

Of course, you can tell you need browser to accept cookies, JavaScript and so on, but it works.

smnbbrvsmnbbrv
14k9 gold badges49 silver badges87 bronze badges

The header you are sending are HTTP headers. The browser takes that as a page request and processes it as a page. And in your case, a page it needs to download.

So adding a redirect header to that confuses the whole process of downloading the file (since headers are collected, generated into one header and then sent to the browser, you can try this by setting multiple redirect headers IIRC)

Ólafur WaageÓlafur Waage
59.5k17 gold badges131 silver badges185 bronze badges

Php File Download Example

Bear in mind, however, the automatic initiation of downloadable files for IE users will trigger the security warning tab. All three of the methods outlined by daremon would show this warning. You simply can't get around this. You will be better served if you provide real links.

I found one workaround for this that relies on javascript, so it's not exactly secure, but for non-secure critical sites it seems to work.

Have a form with a button titled 'download' with the action set to point to the download script, then using javascript put something on the onsubmit handler that strips out the download button and replaces the messaging on the screen. The download should still happen and the screen will change. Obviously, if there's an issue with the download script then it still looks like the download was successful even if it doesn't fire, but it's the best I've got right now.

Darren CrabbDarren Crabb

This is quite old issue, but here is how I achieved it via JS.

Via - https://www.daniweb.com/web-development/php/threads/463652/page-not-redirecting-after-sending-headers-in-php

nikksannikksan

You can try and redirect to the URL plus a parameter that represents the file contents. And in the redirect, you can output the file content for download.

Launch the PHP file which contains the CSV download using:

or

where the JavaScript function popoutWin is

This will open a window, to display the CSV download prompt and then immediately close the window, leaving only the prompt.

brasofilo
22.2k10 gold badges71 silver badges146 bronze badges
ClintonClinton
5731 gold badge7 silver badges11 bronze badges

Here is the answer:
It's work!
You need three different parts of code:
HTML


JQuery


PHP

Hmmmm...

Put the code below in the main javascript of the site.

Explaining:It does the normal redirect with php to some url you will difine and in javascipt it says: If the pathname is the same as the path that redirect made '/url_of_redirect/' then it opens the url on a new page, generating the downlod.

FernandoGirotoFernandoGiroto
Download

Not the answer you're looking for? Browse other questions tagged phpredirectheader or ask your own question.

An Object-Oriented library to convert video/audio files with FFmpeg / AVConv.

Check another amazing repo: PHP FFMpeg extras, you will find lots of Audio/Video formats there.

Your attention please

How this library works:

This library requires a working FFMpeg install. You will need both FFMpeg and FFProbe binaries to use it.Be sure that these binaries can be located with system PATH to get the benefit of the binary detection,otherwise you should have to explicitly give the binaries path on load.

Known issues:

  • Using rotate and resize will produce a corrupted output when usinglibav 0.8. The bug is fixed in version 9. This bug does notappear in latest ffmpeg version.

Installation

The recommended way to install PHP-FFMpeg is through Composer.

Basic Usage

open('video.mpg');$video ->filters() ->resize(new FFMpegCoordinateDimension(320, 240)) ->synchronize();$video ->frame(FFMpegCoordinateTimeCode::fromSeconds(10)) ->save('frame.jpg');$video ->save(new FFMpegFormatVideoX264(), 'export-x264.mp4') ->save(new FFMpegFormatVideoWMV(), 'export-wmv.wmv') ->save(new FFMpegFormatVideoWebM(), 'export-webm.webm');'>

Documentation

This documentation is an introduction to discover the API. It's recommendedto browse the source code as it is self-documented.

FFMpeg

FFMpegFFMpeg is the main object to use to manipulate medias. To build it,use the static FFMpegFFMpeg::create:

FFMpeg will autodetect ffmpeg and ffprobe binaries. If you want to give binarypaths explicitly, you can pass an array as configuration. A PsrLoggerLoggerInterfacecan also be passed to log binary executions.

'/opt/local/ffmpeg/bin/ffmpeg', 'ffprobe.binaries' => '/opt/local/ffmpeg/bin/ffprobe', 'timeout' => 3600, // The timeout for the underlying process 'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use), $logger);'>

Manipulate media

FFMpegFFMpeg creates media based on URIs. URIs could be either a pointer to alocal filesystem resource, an HTTP resource or any resource supported by FFmpeg.

Note: To list all supported resource type of your FFmpeg build, use the-protocols command:

To open a resource, use the FFMpegFFMpeg::open method.

open('video.mpeg');'>

Two types of media can be resolved: FFMpegMediaAudio and FFMpegMediaVideo.A third type, FFMpegMediaFrame, is available through videos.

Video

FFMpegMediaVideo can be transcoded, ie: change codec, isolate audio orvideo. Frames can be extracted.

Transcoding

You can transcode videos using the FFMpegMediaVideo:save method. You willpass a FFMpegFormatFormatInterface for that.

Please note that audio and video bitrate are set on the format. You can disable the -b:v option by setting the kilo bitrate to 0.

Transcoding progress can be monitored in realtime, see Format documentationbelow for more information.

Extracting image

You can extract a frame at any timecode using the FFMpegMediaVideo::framemethod.

This code returns a FFMpegMediaFrame instance corresponding to the second 42.You can pass any FFMpegCoordinateTimeCode as argument, see dedicateddocumentation below for more information.

frame(FFMpegCoordinateTimeCode::fromSeconds(42));$frame->save('image.jpg');'>

If you want to extract multiple images from the video, you can use the following filter:

By default, this will save the frames as jpg images.

You are able to override this using setFrameFileType to save the frames in another format:

setFrameFileType($frameFileType);$video->addFilter($filter);'>
Clip

Cuts the video at a desired point. Use input seeking method. It is faster option than use filter clip.

The clip filter takes two parameters:

  • $start, an instance of FFMpegCoordinateTimeCode, specifies the start point of the clip
  • $duration, optional, an instance of FFMpegCoordinateTimeCode, specifies the duration of the clip

On clip you can apply same filters as on video. For example resizing filter.

clip(FFMpegCoordinateTimeCode::fromSeconds(30), FFMpegCoordinateTimeCode::fromSeconds(15));$clip->filters()->resize(new FFMpegCoordinateDimension(320, 240), FFMpegFiltersVideoResizeFilter::RESIZEMODE_INSET, true);$clip->save(new FFMpegFormatVideoX264(), 'video.avi');'>
Generate a waveform

You can generate a waveform of an audio file using the FFMpegMediaAudio::waveformmethod.

This code returns a FFMpegMediaWaveform instance.You can optionally pass dimensions as the first two arguments and an array of hex string colors for ffmpeg to use for the waveform, see dedicateddocumentation below for more information.

The output file MUST use the PNG extension.

If you want to get a waveform from a video, convert it in an audio file first.

open( 'video.mp4' );// Set an audio format$audio_format = new FFMpegFormatAudioMp3();// Extract the audio into a new file as mp3$video->save($audio_format, 'audio.mp3');// Set the audio file$audio = $ffmpeg->open( 'audio.mp3' );// Create the waveform$waveform = $audio->waveform();$waveform->save( 'waveform.png' );'>
Filters

You can apply filters on FFMpegMediaVideo with the FFMpegMediaVideo::addFiltermethod. Video accepts Audio and Video filters.

You can build your own filters and some are bundled in PHP-FFMpeg - they areaccessible through the FFMpegMediaVideo::filters method.

Filters are chainable

Rotate

Rotates a video to a given angle.

filters()->rotate($angle);'>

The $angle parameter must be one of the following constants :

  • FFMpegFiltersVideoRotateFilter::ROTATE_90: 90° clockwise
  • FFMpegFiltersVideoRotateFilter::ROTATE_180: 180°
  • FFMpegFiltersVideoRotateFilter::ROTATE_270: 90° counterclockwise
Resize

Resizes a video to a given size.

The resize filter takes three parameters:

  • $dimension, an instance of FFMpegCoordinateDimension
  • $mode, one of the constants FFMpegFiltersVideoResizeFilter::RESIZEMODE_* constants
  • $useStandards, a boolean to force the use of the nearest aspect ratio standard.

Download Files Using Php

If you want a video in a non-standard ratio, you can use the padding filter to resize your video in the desired size, and wrap it into black bars.

filters()->pad($dimension);'>

The pad filter takes one parameter:

  • $dimension, an instance of FFMpegCoordinateDimension

Don't forget to save it afterwards.

Watermark

Watermark a video with a given image.

filters() ->watermark($watermarkPath, array( 'position' => 'relative', 'bottom' => 50, 'right' => 50, ));'>

The watermark filter takes two parameters:

$watermarkPath, the path to your watermark file.$coordinates, an array defining how you want your watermark positioned. You can use relative positioning as demonstrated above or absolute as such:

Framerate

Changes the frame rate of the video.

filters()->framerate($framerate, $gop);'>

The framerate filter takes two parameters:

  • $framerate, an instance of FFMpegCoordinateFrameRate
  • $gop, a GOP value (integer)
Synchronize

Synchronizes audio and video.

Some containers may use a delay that results in desynchronized outputs. Thisfilter solves this issue.

Clip

Cuts the video at a desired point.

filters()->clip(FFMpegCoordinateTimeCode::fromSeconds(30), FFMpegCoordinateTimeCode::fromSeconds(15));'>

The clip filter takes two parameters:

  • $start, an instance of FFMpegCoordinateTimeCode, specifies the start point of the clip
  • $duration, optional, an instance of FFMpegCoordinateTimeCode, specifies the duration of the clip
Crop

Crops the video based on a width and height(a Point)

It takes two parameters:

  • $point, an instance of FFMpegCoordinatePoint, specifies the point to crop
  • $dimension, an instance of FFMpegCoordinateDimension, specifies the dimension of the output video

Audio

FFMpegMediaAudio can be transcoded too, ie: change codec, isolate audio orvideo. Frames can be extracted.

Transcoding

You can transcode audios using the FFMpegMediaAudio:save method. You willpass a FFMpegFormatFormatInterface for that.

Please note that audio kilobitrate is set on the audio format.

open('track.mp3');$format = new FFMpegFormatAudioFlac();$format->on('progress', function ($audio, $format, $percentage) { echo '$percentage % transcoded';});$format ->setAudioChannels(2) ->setAudioKiloBitrate(256);$audio->save($format, 'track.flac');'>

Transcoding progress can be monitored in realtime, see Format documentationbelow for more information.

Php File Download Example Project

Filters

You can apply filters on FFMpegMediaAudio with the FFMpegMediaAudio::addFiltermethod. It only accepts audio filters.

You can build your own filters and some are bundled in PHP-FFMpeg - they areaccessible through the FFMpegMediaAudio::filters method.

Clipping

Cuts the audio at a desired point.

Metadata

Add metadata to audio files. Just pass an array of key=value pairs of allmetadata you would like to add. If no arguments are passed into the filterall metadata will be removed from input file. Currently supported data istitle, artist, album, artist, composer, track, year, description, artwork

filters()->addMetadata(['title' => 'Some Title', 'track' => 1]);//remove all metadata and video streams from audio file$audio->filters()->addMetadata();'>

Add artwork to the audio file

NOTE: at present ffmpeg (version 3.2.2) only supports artwork output for .mp3files

Resample

Resamples an audio file.

filters()->resample($rate);'>

Php File Installer

The resample filter takes two parameters :

  • $rate, a valid audio sample rate value (integer)

Frame

A frame is an image at a timecode of a video; see documentation above aboutframe extraction.

You can save frames using the FFMpegMediaFrame::save method.

This method has a second optional boolean parameter. Set it to true to getaccurate images; it takes more time to execute.

Gif

A gif is an animated image extracted from a sequence of the video.

You can save gif files using the FFMpegMediaGif::save method.

open( '/path/to/video' );$video ->gif(FFMpegCoordinateTimeCode::fromSeconds(2), new FFMpegCoordinateDimension(640, 480), 3) ->save($new_file);'>

This method has a third optional boolean parameter, which is the duration of the animation.If you don't set it, you will get a fixed gif image.

Concatenation

This feature allows you to generate one audio or video file, based on multiple sources.

There are two ways to concatenate videos, depending on the codecs of the sources.If your sources have all been encoded with the same codec, you will want to use the FFMpegMediaConcatenate::saveFromSameCodecs which has way better performances.If your sources have been encoded with different codecs, you will want to use the FFMpegMediaConcatenate::saveFromDifferentCodecs.

The first function will use the initial codec as the one for the generated file.With the second function, you will be able to choose which codec you want for the generated file.

You also need to pay attention to the fact that, when using the saveFromDifferentCodecs method,your files MUST have video and audio streams.

In both cases, you will have to provide an array of files.

To concatenate videos encoded with the same codec, do as follow:

The boolean parameter of the save function allows you to use the copy parameter which accelerates drastically the generation of the encoded file.

To concatenate videos encoded with the different codec, do as follow:

open( '/path/to/video' );$format = new FFMpegFormatVideoX264();$format->setAudioCodec('libmp3lame');$video ->concat(array('/path/to/video1', '/path/to/video2')) ->saveFromDifferentCodecs($format, '/path/to/new_file');'>

More details about concatenation in FFMPEG can be found here, here and here.

AdvancedMedia

AdvancedMedia may have multiple inputs and multiple outputs.

This class has been developed primarily to use with -filter_complex.

So, its filters() method accepts only filters that can be used inside -filter_complex command.AdvancedMedia already contains some built-in filters.

Base usage

For example:

This code takes 2 input videos, stacks they horizontally in 1 output video and adds to this new video the audio from the first video.(It is impossible with simple filtergraph that has only 1 input and only 1 output).

Complicated example

A more difficult example of possibilities of the AdvancedMedia. Consider all input videos already have the same resolution and duration. ('xstack' filter has been added in the 4.1 version of the ffmpeg).

openAdvanced($inputs);$advancedMedia->filters() ->custom('[0:v]', 'negate', '[v0negate]') ->custom('[1:v]', 'edgedetect', '[v1edgedetect]') ->custom('[2:v]', 'hflip', '[v2hflip]') ->custom('[3:v]', 'vflip', '[v3vflip]') ->xStack('[v0negate][v1edgedetect][v2hflip][v3vflip]', XStackFilter::LAYOUT_2X2, 4, '[resultv]');$advancedMedia ->map(array('0:a'), new Mp3(), 'video_1.mp3') ->map(array('1:a'), new Flac(), 'video_2.flac') ->map(array('2:a'), new Wav(), 'video_3.wav') ->map(array('3:a'), new Aac(), 'video_4.aac') ->map(array('[resultv]'), new X264('aac', 'libx264'), 'output.mp4') ->save();'>

This code takes 4 input videos, then the negates the first video, stores result in [v0negate] stream, detects edges in the second video, stores result in [v1edgedetect] stream, horizontally flips the third video, stores result in [v2hflip] stream, vertically flips the fourth video, stores result in [v3vflip] stream, then takes this 4 generated streams ans combine them in one 2x2 collage video.Then saves audios from the original videos into the 4 different formats and saves the generated collage video into the separate file.

File Downloader Script

As you can see, you can take multiple input sources, perform the complicated processing for them and produce multiple output files in the same time, in the one ffmpeg command.

Just give me a map!

You do not have to use -filter_complex. You can use only -map options. For example, just extract the audio from the video:

Customisation

If you need you can extra customize the result ffmpeg command of the AdvancedMedia:

openAdvanced($inputs);$advancedMedia ->setInitialParameters(array('the', 'params', 'that', 'will', 'be', 'added', 'before', '-i', 'part', 'of', 'the', 'command')) ->setAdditionalParameters(array('the', 'params', 'that', 'will', 'be', 'added', 'at', 'the', 'end', 'of', 'the', 'command'));'>

Formats

A format implements FFMpegFormatFormatInterface. To save to a video file,use FFMpegFormatVideoInterface, and FFMpegFormatAudioInterface foraudio files.

A format can also extend FFMpegFormatProgressableInterface to get realtimeinformation about the transcoding.

Predefined formats already provide progress information as events.

The callback provided for the event can be any callable.

Add additional parameters

You can add additional parameters to your encoding requests based on your video format.

The argument of the setAdditionalParameters method is an array.

setAdditionalParameters(array('foo', 'bar'));$video->save($format, 'video.avi');'>
Add initial parameters

You can also add initial parameters to your encoding requests based on your video format. This can be expecially handy in overriding a default input codec in FFMpeg.

The argument of the setInitialParameters method is an array.

Create your own format

The easiest way to create a format is to extend the abstractFFMpegFormatVideoDefaultVideo and FFMpegFormatAudioDefaultAudio.and implement the following methods.

setAudioCodec($audioCodec) ->setVideoCodec($videoCodec); } public function supportBFrames() { return false; } public function getAvailableAudioCodecs() { return array('wmav2'); } public function getAvailableVideoCodecs() { return array('wmv2'); }}'>

Coordinates

FFMpeg uses many units for time and space coordinates.

  • FFMpegCoordinateAspectRatio represents an aspect ratio.
  • FFMpegCoordinateDimension represent a dimension.
  • FFMpegCoordinateFrameRate represent a framerate.
  • FFMpegCoordinatePoint represent a point. (Supports dynamic points since v0.10.0)
  • FFMpegCoordinateTimeCode represent a timecode.

FFProbe

FFMpegFFProbe is used internally by FFMpegFFMpeg to probe medias. You canalso use it to extract media metadata.

format('/path/to/video/mp4') // extracts file informations ->get('duration'); // returns the duration property'>

Validating media files

(since 0.10.0)You can validate media files using PHP-FFMpeg's FFProbe wrapper.

Using with Silex Microframework

The service provider is easy to set up:

register(new FFMpegFFMpegServiceProvider());$video = $app['ffmpeg']->open('video.mpeg');'>

Available options are as follow:

License

This project is licensed under the MIT license.

Music: 'Favorite Secrets' by Waylon ThorntonFrom the Free Music ArchiveCC BY NC SA

Music: 'Siesta' by JahzzarFrom the Free Music ArchiveCC BY SA