$tempDir = '/download/file/here';
$finalDir = '/keep/file/here';
$imageUrl = 'http://www.example.com/image.jpg';
exec("cd $tempDir && wget --quiet $imageUrl");
if (!file_exists("$tempDir/image.jpg")) {
throw new Exception('Failed while trying to download image');
}
if (rename("$tempDir/image.jpg", "$finalDir/new-image-name.jpg") === false) {
throw new Exception('Failed while trying to move image file from temp dir to final dir');
}
// ... image validation ...
// Fetch all headers from URL
$data = get_headers($image_url, true);
// Check if content encoding is set
$content_encoding = isset($data['Content-Encoding']) ? $data['Content-Encoding'] : null;
// Set gzip decode flag
$gzip_decode = ($content_encoding == 'gzip') ? true : false;
if ($gzip_decode)
{
// Get contents and use gzdecode to "unzip" data
file_put_contents($dest_path, gzdecode(file_get_contents($image_url)));
}
else
{
// Use copy method
copy($image_url, $dest_path);
}