Salvare un file remoto in locale è un'operazione relativamente semplice in PHP.
Possiamo creare la seguente classe:
class My_Getter {
public $url;
public $fileName;
public function __construct($uri, $name) {
$this->url = $uri;
$this->fileName = $name;
}
private function _getFile() {
$output = '';
if(filter_var($this->url, FILTER_VALIDATE_URL)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
if ($curl_errno > 0) {
$output = null;
} else {
$output = $data;
}
} else {
$output = null;
}
return $output;
}
public function save() {
$data = $this->_getFile();
$result = true;
if(!is_null($data)) {
file_put_contents($this->fileName, $data);
} else {
$result = false;
}
return $result;
}
}
Esempio d'uso:
$myGetter = new My_Getter('http://domain/file.txt', 'file.txt');
if($myGetter->save()) {
//...
}