Wednesday, February 5, 2020

How to download files from AWS CDN using PHP?

We have implemented the below code for download any type of file from AWS server using PHP. Please refer and implement same.


<?php 


  function downloadAWSFiles()
   {
       try{
           $fileName   = 'https://project021.s3.ap-south-1.amazonaws.com/p1dvtscgk06mh1t2sj6o3imne64.pdf';
           $fileExt   =  strtolower(pathinfo($fileName, PATHINFO_EXTENSION));           
           $pos    = strrpos($fileName, '/');
           $downloadFile  = substr($fileName, $pos + 1);
           $newFileName  = 'newFiles.'.$fileExt;
           switch($fileExt) {
               case 'pdf': $mime = 'application/pdf'; break;
               case 'zip': $mime = 'application/zip'; break;
               case 'jpeg': $mime = 'image/jpeg'; break;
               case 'jpg': $mime = 'image/jpg'; break;
               case 'png': $mime = 'image/png'; break;
               default: $mime = 'application/force-download';
             }
           header('Pragma: public');     // required
           header('Expires: 0');     // no cache
           header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
           header('Cache-Control: private', false);
           header('Content-Type: ' . $mime);
           header('Content-Disposition: attachment; filename="' . $newFileName .'"');
           header('Content-Transfer-Encoding: binary');
           header('Connection: close');
           readfile("https://s3.ap-south-1.amazonaws.com/" . 'xxxx' . "/" . $downloadFile);
           exit();
       }catch(Exception $e){
       return array();
       }    
   }
   
   Call to the function 
   
   downloadAWSFiles();
   
   
?>

No comments:

Post a Comment