Create and launch a download with PHP

In this article I am going to explain how to launch a file download using PHP with headers. With this functionality you will be able to avoid the typical direct link to your files through tags ahref or other similar way.

With this methodology we couldlaunch downloads with a unique id and a route of the style /download-file/ab123jri123kp or even through unique SEO-readable names like the best laptop for programming.jpg”.

In this tutorial I am going to focus on explaining the most important parts of this PHP functionality, showing you how to configure the most complex ones and finally I will leave you a copy and paste snippet so you can try it.

Content

  • Steps to create a download in PHP
  • Configuring the PHP download headers
  • Send the content of the file to be downloaded by the user
  • Snippet php to launch the download in the file browser
  • Do you already know how to launch downloads with PHP?

Steps to create a download in PHP

To create any file download in PHP You will always have to follow the same guidelines:

  1. Know the path of the file to download.
  2. Know your name.
  3. configure the headers of content-type “Content-Type”.
  4. Calculate the size of the file.
  5. Indicate a new name to the file.
  6. Open the file to send through the download.
  7. Print the content.
  8. Close the reading of the file.

In the following I am going to focus on seeing only the most important and complex parts of this php script.

Configuring the PHP download headers

For creating and manipulating headers http with php we will always take into account the same keys:

  • The PHP headers that we will use will indicate to the visitor (their browser) that the content being sent is that of a file and a page.
  • Header configuration in PHP is always done with the same command: headers.

These are general guidelines for all headend configurations, so for send a response in the form of a downloadable file We will indicate the following headers:

<?php
$fichero_local = __DIR__ . '/mi-imagen.jpg'; //ruta al fichero en los directorios locales
$nombre_fichero = 'imagen-aprender-a-programar-php.jpg'; //nombre del fichero que se descargará el usuario
 header('Cache-control: private');
 header('Content-Type: application/octet-stream'); 
 header('Content-Length: '.filesize($local_file));
 header('Content-Disposition: filename='.$nombre_fichero);
?>

In these headers I have indicated:

  1. The content-type “application/octet-stream”.
  2. The size of the file in “Content-Length”
  3. Finally, the name that I want to give to the file when the user downloads it.

In this way the local file is called “my-image.jpg” and the user will download the image with the name “image-learn-to-program-php.jpg”.

But we are not finished yet, we have to finish the script by sending the content of the file to be downloaded.

Send the content of the file to be downloaded by the user

Now let’s send the visitor the content of the file to downloadsince until now we had only configured, for the browser, that the content to be sent is a file and not an HTML page.

We will manipulate the file with three php functions:

  • fopen: which allows you to open a file for reading.
  • fread: php function that gets the content of the file.
  • close: function that closes the file and releases it.

The code that follows the headers for this tutorial is as follows:

<?php
 //abrimos el fichero
 $file = fopen($fichero_local , "rb");

//imprimimos el contenido del fichero al navegador
print fread ($file, filesize($fichero_local )); 
 
//cerramos el fichero abierto
fclose($file);
?>

Simple right? Now, to finish, all that remains is to explain how all the code would look together.

Snippet php to launch the download in the file browser

Next I leave you the complete script to launch the download of a file.

Depending on your specific case, you will have to change the paths of the local file and its name. For the rest, the code is fully functional and adapted to any download, be it a file zip or an image of any kind.

<?php
$fichero_local = __DIR__ . '/mi-imagen.jpg'; //ruta al fichero en los directorios locales
$nombre_fichero = 'imagen-aprender-a-programar-php.jpg'; //nombre del fichero que se descargará el usuario

if( file_exists($fichero_local ) && is_file($fichero_local) ) { //compruebo, por si acaso, que el fichero exista en el sistema

	header('Cache-control: private');
	header('Content-Type: application/octet-stream'); 
	header('Content-Length: '.filesize($local_file));
	header('Content-Disposition: filename='.$nombre_fichero);
 
    // flush content
    flush();

     //abrimos el fichero
     $file = fopen($fichero_local , "rb");

     //imprimimos el contenido del fichero al navegador
     print fread ($file, filesize($fichero_local )); 
 
     //cerramos el fichero abierto
     fclose($file);

} else {

    die('Error:  El fichero  '.$fichero_local .' no existe!');  //termino la ejecución de código por que el fichero no existe.

}
?>

Do you already know how to launch downloads with PHP?

Well, this is over, I hope this tutorial has been really useful for you and that you start right now to launch downloads with php through any url. I usually use this technique when, after uploading an image with php or html through an intranet, I want to hide the path of its location.

Leave a Reply