Created
July 1, 2018 07:55
-
-
Save jasperf/2a663e529a9160b84e7ff3c7a632ba1c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Class DownloadFile | |
*/ | |
Class DownloadFile | |
{ | |
public $url = 'http://example.com/image.jpg'; | |
public $path = '/path/to/write'; | |
private $filename; | |
private $file; | |
private $mimeType; | |
private $extension; | |
/** | |
* DownloadFile constructor. | |
*/ | |
public function __construct() | |
{ | |
$this->filename = md5(time().rand(0,999)); | |
} | |
/** | |
* downloadFile. | |
*/ | |
public function downloadFile() | |
{ | |
$this->file = file_get_contents($this->url); | |
$this->mimeType = mime_content_type($this->file); | |
switch($this->mimeType) | |
{ | |
case 'image/gif': | |
$this->extension = 'gif'; | |
break; | |
case 'image/jpg': | |
$this->extension = 'jpg'; | |
break; | |
case 'image/jpeg': | |
$this->extension = 'jpg'; | |
break; | |
default: | |
$this->extension = 'unknown'; | |
} | |
file_put_contents($this->path.$this->filename.'.'.$this->extension, $this->file); | |
} | |
/** | |
* getResponse. | |
* | |
* @return array | |
*/ | |
public function getResponse() | |
{ | |
return [ | |
'url' => $this->url, | |
'path' => $this->path, | |
'filename' => $this->filename, | |
'mime_type' => $this->mimeType, | |
'extension' => $this->extension, | |
]; | |
} | |
/** | |
* setUrl | |
* | |
* @param string $url | |
*/ | |
public function setUrl(string $url) | |
{ | |
$this->url = $url; | |
} | |
/** | |
* setPath | |
* | |
* @param string $path | |
*/ | |
public function setPath(string $path) | |
{ | |
$this->path = $path; | |
} | |
} | |
$download = new DownloadFile(); | |
$download->setUrl('http://www.example.com/image.jpg'); | |
$download->setPath('/path/to/write'); | |
$download->downloadFile(); | |
$response = $download->getResponse(); | |
print '<pre>'; | |
print_r($response); | |
print '</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment