Search code snippets, questions, articles...

PHP Script to download image from remote url

This PHP script allows you to download an image from a remote URL. This can be useful when you want to download an image from a website that does not allow direct linking to images.
    $file_url = "https://file_url.jpeg"; // Replace your remote image url here
    $file_name = basename($file_url);
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename="".$file_name.""");

The code above is an example of how to force a file download using PHP.

The file_url variable is set to a URL pointing to a file. The basename function is used to get the filename from the URL.

The content type header is set to application/octet-stream so that the file will download instead of displaying in the browser.

The content-transfer-encoding header is set to binary so that the file is downloaded as a binary file instead of text.

The content-disposition header is set so that the file will download with the specified filename. Finally, the file is read using the readfile() function, and the script exits.

Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet