Last active
June 11, 2025 19:21
-
-
Save NazemMahmud/c13bcaff9d7bc6711adad6f348d42064 to your computer and use it in GitHub Desktop.
Laravel: Download an image from URL and return UploadedFile instance.
This file contains hidden or 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
<?php | |
namespace App\Services; // this will be the namespace according to your file path | |
use Illuminate\Http\UploadedFile; | |
use Illuminate\Support\Facades\Http; | |
use Exception; | |
/** | |
* Follow this gist to find out how to finally unlink and upload image | |
* https://gist.github.com/NazemMahmud/9bef6402f3b0231e532eebda375741bd | |
*/ | |
class FileDownloadService | |
{ | |
private int $timeout = 30; // Set your own timeout value | |
/** | |
* Download an image from URL and return UploadedFile instance | |
* Note: Caller is responsible for cleaning up the temporary file | |
*/ | |
public function downloadImageFile(string $imageUrl): UploadedFile | |
{ | |
$tempPath = null; | |
try { | |
$imageResponse = Http::timeout($this->timeout)->get($imageUrl); | |
if (!$imageResponse->successful()) { | |
throw new Exception("Failed to download image from URL: {$imageUrl}"); | |
} | |
$imageContent = $imageResponse->body(); | |
if (empty($imageContent)) { | |
throw new Exception("Downloaded image content is empty"); | |
} | |
$originalFilename = $this->extractFilenameFromUrl($imageUrl); | |
$tempPath = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . uniqid('img_') . '_' . $originalFilename; | |
if (file_put_contents($tempPath, $imageContent) === false) { | |
throw new Exception("Failed to write image to temporary file"); | |
} | |
$mimeType = mime_content_type($tempPath); | |
if (!$mimeType || !str_starts_with($mimeType, 'image/')) { | |
// Clean up on validation failure | |
if (file_exists($tempPath)) { | |
unlink($tempPath); | |
} | |
throw new Exception('Downloaded file is not a valid image (MIME: ' . $mimeType . ')'); | |
} | |
return new UploadedFile( | |
$tempPath, | |
$originalFilename, | |
$mimeType, | |
null, | |
true | |
); | |
} catch (Exception $e) { | |
// Clean up on error | |
if ($tempPath && file_exists($tempPath)) { | |
unlink($tempPath); | |
} | |
throw $e; | |
} | |
} | |
private function extractFilenameFromUrl(string $url): string | |
{ | |
$filename = basename(parse_url($url, PHP_URL_PATH)); | |
if (empty($filename) || !pathinfo($filename, PATHINFO_EXTENSION)) { | |
$filename = 'file_' . time() . '_' . uniqid() . '.jpg'; | |
} | |
return preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment