Если у вас нет для использования curl, вот как вы могли бы сделать это, используя прямой PHP.
Примечание. Можно установить заголовки, учетные данные и т. Д. При использовании fopen () для извлечения URL-адресов с использованием параметров контекста HTTP .
<?php
class DownloadWithExtension
{
// array for caching mimetypes
public $mimetypes = array();
// create mimetype cache when instantiated
public function __construct() {
// iterate through /etc/mime.types and create a hash with
// mime-types as keys and the first extension as the value.
foreach(preg_grep('/(^#)|(^\s+$)/',
file('/etc/mime.types'), PREG_GREP_INVERT) as $line) {
$minfo = preg_split('/\t+/', $line);
if (count($minfo) > 1) {
$this->mimetypes[$minfo[0]] = trim(array_shift(explode(' ', $minfo[1])));
}
}
}
// download $url and save as $prefix while automatically
// determining appropriate extension.
// @param $url - URL to download
// @param $prefix - Filename to save to (without extension)
// @return filename used
public function get($url, $prefix) {
$mimetype = NULL;
$filename = NULL;
$src = fopen($url, 'r');
if (! $src) {
throw new Exception('Failed to open: ' . $url);
}
$meta = stream_get_meta_data($src);
foreach($meta['wrapper_data'] as $header){
if (preg_match('/^content-type: ([^\s]+)/i', $header, &$matches)) {
$mimetype = $matches[1];
break;
}
}
$extension = @$this->mimetypes[$mimetype];
// default to .bin if the mime-type could not be determined
$filename = sprintf('%s.%s', $prefix, $extension ? $extension : 'bin');
$dst = fopen($filename, 'w');
if (! ($dst && stream_copy_to_stream($src, $dst) &&
fclose($src) && fclose($dst))) {
throw new Exception('An error occurred while saving the file!');
}
return $filename;
}
}
$d = new DownloadWithExtension();
$url = 'http://example.com?file=3838438';
$filename = $d->get($url, '/tmp/myfile');
print(sprintf("Saved %s as %s\n", $url, $filename));