Create Image From Url Any File Type

Create Image From Url Any File Type

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Creating Image Resources from Any URL in PHP

PHP provides specific entry points for loading image data: imagecreatefromgif(), imagecreatefromjpeg(), and imagecreatefrompng(). While these functions handle their respective formats well, they require you to know the file type beforehand. If you are working with a generic URL like http://sample.com/image.png where the filename extension might be unreliable or missing entirely, relying solely on getimagesize() is often insufficient because it returns false if the content type isn't recognized as one of the supported image formats.

The core limitation here is that PHP's GD library does not expose a single "catch-all" function like imagecreatefromany(). To handle images of any valid type from a remote URL without hardcoding checks for every known format, you need to leverage the underlying resource handling capabilities provided by the ImageMagick or GD libraries in a dynamic way.

The most robust approach involves using the getimagesize() function not just to check dimensions, but specifically to inspect its third return value: the MIME type. This string tells you exactly what format the server sent back, regardless of the URL filename. You can then map that MIME type directly to the corresponding PHP image creation function.

Here is a practical implementation pattern using GD:

function getImageFromUrl($url) {
    // Fetch the raw data to avoid loading the entire image into memory immediately if possible
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    $imageData = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        throw new Exception("Failed to fetch image: HTTP {$httpCode}");
    }

    // getimagesize returns false on failure or unsupported types
    $info = @getimagesize($imageData);

    if (!$info) {
        // Check if it might be a WebP or AVIF that older GD versions miss, 
        // or simply fail the check.
        throw new Exception("Unable to identify image format.");
    }

    $type = $info['mime'];
    $width = $info[0];
    $height = $info[1];

    if (strpos($type, 'image/gif') === 0) {
        return imagecreatefromgif($imageData);
    } elseif (strpos($type, 'image/jpeg') === 0) {
        return imagecreatefromjpeg($imageData);
    } elseif (strpos($type, 'image/png') === 0) {
        return imagecreatefrompng($imageData);
    } elseif (strpos($type, 'image/webp') === 0) {
        return imagecreatefromwebp($imageData); // Available in PHP >= 7.3
    }

    throw new Exception("Unsupported image format: {$type}");
}

This approach handles the MIME type mapping dynamically. It also includes a check for WebP, which is widely used now but wasn't supported by GD until PHP 7.3. If you are running an older version of PHP, you will encounter errors when attempting to load WebP images using this method unless you install additional extensions or rely on ImageMagick via imageloadimage().

A significant trade-off with getimagesize() is that it expects a valid resource stream. When passing a string returned by cURL directly, it works in most environments, but some strict configurations might require file uploads (tmpfile or fopen) to handle the data correctly depending on the PHP version and allow_url_fopen settings.

If you are working within the Laravel ecosystem, consider leveraging packages that abstract this complexity. Libraries like spatie/image or similar tools often wrap these low-level calls, providing a fluent interface that handles format detection and resizing automatically. For instance, Spatie's Image library uses ImageMagick under the hood for complex manipulations but can also work with GD for simple needs.

composer require spatie/image

Using such a library removes the need to manually switch between imagecreatefromjpeg and imagecreatefrompng. You simply pass the URL or file path, and the library handles the format detection and resource creation. This is particularly useful when building image manipulation pipelines where you don't want to clutter your logic with MIME type strings.

However, keep in mind that loading images from URLs into memory can be heavy if you are processing high-resolution assets. Always validate the URL response code before attempting to parse the binary data. If getimagesize() returns false despite a 200 status, the server likely served an image with an incorrect Content-Type header or the file is corrupted. In those cases, debugging requires inspecting the raw headers and potentially falling back to ImageMagick's convert command via shell execution if available on the server.

Our network