How to Save Remote Images Locally Using PHP

This tutorial explains how to install the CURL extension, retrieve a remote image with file_get_contents, create a local directory, generate a unique filename, and save the image using file_put_contents in PHP, providing a complete, step‑by‑step guide for developers.

php Courses
php Courses
php Courses
How to Save Remote Images Locally Using PHP

Install CURL Extension

To download images from remote servers, ensure the CURL extension is installed; check with php -m | grep curl. If not present, install it.

Get Remote Image URL

Use file_get_contents() to fetch the image data from a URL, e.g.,

$url = 'https://example.com/image.jpg'; $imageData = file_get_contents($url);

Create Local Save Path

Create a directory for storing images using mkdir(), e.g.,

$savePath = '/var/www/images/'; mkdir($savePath, 0755, true);

Generate Local Filename

Generate a unique filename with uniqid() or a timestamp, e.g.,

$fileName = time() . '.jpg';

Save Image Locally

Combine the path and filename and write the image data using file_put_contents():

$savePath = '/var/www/images/';
$fileName = time() . '.jpg';
$localFilePath = $savePath . $fileName;
file_put_contents($localFilePath, $imageData);

These steps complete the process of saving a remote image to the local server.

Full Example Code

$url = 'https://example.com/image.jpg';
$savePath = '/var/www/images/';
$fileName = time() . '.jpg';
$localFilePath = $savePath . $fileName;

$imageData = file_get_contents($url);
mkdir($savePath, 0755, true);
file_put_contents($localFilePath, $imageData);

Conclusion

The article demonstrates how to fetch a remote image, create a storage directory, generate a unique filename, and save the image locally using PHP, providing a practical solution for developers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend Developmentfile-handling
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.