2

I want to download files from remote server and save those files in my server exactly as this answer here

https://stackoverflow.com/a/48141751/9625566

I am using his code but the problem is it's not saving the file with original remote-server file name, its saving the file as "6897823", but I want the file name exactly as on remote server which is

"fantastic.beasts.and.where.to.find.them.(2016).eng.1cd.(6897823).zip"

This is the example link

https://dl.opensubtitles.org/en/download/src-api/vrf-f58b0bc4/sub/6897823

I have tried CURL & file_get_content(), For both i must provide a default filename, they don't get the file name from the link,

<?php 

  $url = "https://dl.opensubtitles.org/en/download/src-api/vrf-f58b0bc4/sub/6897823";

  class Downloader 
 {
    private $path;
    public $filename;

    public function __construct()
    {
        $this->path = dirname(__FILE__);
    }

    public function getFile($url)
    {
        $fileName = $this->getFileName($url);
        if(!file_exists($this->path."/".$fileName)){
            $this->downloadFile($url,$fileName);
        }

        return file_get_contents($this->path."/".$fileName);
    }
    public function getFileName($url)
    {
        $slugs = explode("/", $url);
        $this->filename = $slugs[count($slugs)-1];
        return $this->filename;
    }

    private function downloadFile($url,$fileName)
    {
        //This is the file where we save the information
        $fp = fopen ($this->path.'/'.$fileName, 'w+');
        //Here is the file we are downloading, replace spaces with %20
        $ch = curl_init(str_replace(" ","%20",$url));
        curl_setopt($ch, CURLOPT_TIMEOUT, 50);
        // write curl response to file
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        // get curl response
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
    }     
}

  $downloader = new Downloader();
  $content = $downloader->getFile($url);

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment;     filename="'.$downloader->filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($content));

print $content;
exit;

?>

I am expecting the filename to be

"fantastic.beasts.and.where.to.find.them.(2016).eng.1cd.(6897823).zip"

But the output is 6897823

Thanks for reading.

0 Answers0