Export password protected csv from a DB

Asked

Viewed 114 times

1

It is possible to generate a file CSV protegido por Senha from a banco MySql using PHP? the password is to open the file in the client.

I use this PHP script to generate the CSV file:

<?php  
      //export.php  
 if(isset($_POST["export"]))  
 {  
      $connect = mysqli_connect("localhost", "root", "", "simrede"); 
      if (mysqli_connect_errno())
      {
      echo "Falha ao fazer conexão: " . mysqli_connect_error();
      }

    // Set utf8
      mysqli_set_charset($connect,"utf8");
      $connect->set_charset('utf8');
      header('Content-Type: text/csv; charset=utf-8');  
      header('Content-Disposition: attachment; filename=Cadastro_Alunos-Simrede.csv');  
      $output = fopen("php://output", "w");  
      fputcsv($output, array('lastname', 'firstname', 'department', 'institution', 'username',  'email', 'city', 'course1', 'password'),';');  
      $query = "SELECT * from cs_alunos ORDER BY institution";  
      $result = mysqli_query($connect, $query);  
      while($row = mysqli_fetch_assoc($result))  
      {
           fputcsv($output, $row,";");  
      }  
      fclose($output);  
 }  
 ?>
  • It is necessary to clarify if the password is required to request the file on the server or password to open the file on the client.

  • @fernandosavio added the information in the text of the question.

1 answer

1


The quick answer is that there is no way a CSV file can be password protected. But there are methods to get a satisfactory result.

One of them would be to compact the .csv and protect the .zip per password. It is an efficient method because, in addition to protecting the file for reading, it also decreases the download of the file to the client.

In PHP a file .zip can be created using the class ZipArchive.

Example:

<?php

$zip = new ZipArchive();

if($zip->open('download/meu_csv_protegido.zip', ZIPARCHIVE::CREATE) !== true) {
    return false;  // Não foi possível criar o zip
}

$zip->addFile('meus_dados.csv');
$zip->setPassword('minha_senha');
$zip->close();
  • How to do this using the above question script?

  • I added an example of how to create a zip file... After the $zip->close() just send the file to the client and, if applicable, delete the file later.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.