Download image from URL using php code?

Download image from URL using php code?

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

Stefan Bogdanescu

Founder & Senior Architect

Downloading Images from URLs in PHP: Path Resolution and Security Considerations

Your current implementation fails because of a fundamental misunderstanding of how file paths work relative to your document root, combined with potential security implications when handling remote data. The error [function.file-put-contents]: failed to open stream: No such file or directory indicates that file_put_contents cannot find the target location you specified.

In your code, you defined $img_path = '/images/';. This is an absolute path starting from the root of your operating system (e.g., /home/user/wamp/www/images/). Unless your web server is configured to serve files directly from the system root, this path will never resolve correctly within a standard installation like WAMP or Apache. Relative paths are required here. You need to construct the full filesystem path by concatenating the script's directory with the relative folder name.

$directory = dirname(__FILE__) . '/images';
$img_path = $directory . '/' . basename($_POST['text']); // Sanitize filename later

Using dirname(__FILE__) ensures you are always pointing to the correct directory regardless of where the script is called from. However, simply fixing the path isn't enough; you must also address how PHP handles remote resources and ensure the destination directory actually exists before writing to it.

Handling Remote Content and MIME Types

When fetching content with file_get_contents, you are treating the image as raw binary data. While this works for saving files, you must verify that the URL actually returns an image and not HTML or a redirect loop. If the remote server redirects the request (common with Google images), file_get_contents might follow the redirect automatically depending on your configuration, potentially returning 301/302 headers which break binary file handling.

To handle this robustly, you should explicitly disable following redirects if you intend to handle them manually, or ensure your user agent string is set correctly so servers don't block your request. More importantly, you must verify the Content-Type header returned by the remote server matches an image type before attempting to save it. This prevents accidentally saving malicious HTML files as images.

$context = stream_context_create([
    'http' => [
        'ignore_errors' => true, // Handle redirects or 404s gracefully
        'user_agent' => 'Mozilla/5.0'
    ]
]);

$content = @file_get_contents($_POST['text'], false, $context);

if ($content === false) {
    echo "Failed to fetch content.";
} else {
    $mimeType = mime_content_type($content); // Or check headers if available
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    
    if (!in_array($mimeType, $allowedTypes)) {
        echo "The URL does not point to a valid image.";
    } else {
        file_put_contents($img_path, $content);
    }
}

Security Risks in File Paths

Your original code takes the user input directly into the filename logic. This is a critical vulnerability known as Path Traversal or arbitrary file creation. If a user inputs ../../etc/passwd or attempts to overwrite a critical system file, your script will execute it.

You must sanitize the filename derived from the URL. A safe approach is to extract only the filename component (the part after the last /) and strip any path information. Additionally, you should validate that the target directory exists and is writable before attempting to write. If the directory images does not exist, file_put_contents will fail with the exact error you saw. Always create the directory programmatically if necessary using mkdir, setting appropriate permissions immediately.

$safeFilename = basename($_POST['text']); // Removes path info like ../
$fullPath = $directory . '/' . $safeFilename;

if (!is_dir($directory)) {
    mkdir($directory, 0755, true);
}

file_put_contents($fullPath, $content);

Modern Alternatives with Laravel

If you are building a larger application, raw PHP file handling offers little flexibility. Frameworks like Laravel provide built-in methods to handle this scenario more cleanly and securely. The Illuminate\Http\DownloadResponse class allows you to force a browser download or save the file directly to disk without manually managing streams or binary data conversion.

For instance, using the Laravel facade, you can retrieve the resource and save it with a single method:

use Illuminate\Support\Facades\Storage;

$response = Storage::download('https://www.google.com/images/srpr/logo3w.png', 'logo.png');
// Or specifically saving to a directory if configured in filesystem
Storage::disk('local')->putFileAs('/images', $response, 'logo.png');

This approach abstracts away the stream context and path resolution logic while maintaining security best practices. It also integrates seamlessly with Laravel's event system, allowing you to trigger notifications or log actions when an image is successfully cached. If you are looking for more advanced caching strategies or secure file handling patterns in a PHP environment, resources like https://laravelcompany.com offer deeper insights into managing assets within modern stacks.

Conclusion

To resolve your specific error, switch from absolute paths to relative paths constructed via dirname(__FILE__), ensure the directory exists, and strictly sanitize any user-derived filenames. Always validate the content type of remote files before saving them as images to prevent executing malicious scripts disguised as media.

Our network