PHP Downloading With file_get_contents()

Code Snippets Downloading With File Get Contents
Share:

About

In this code snippet, we’ll learn how to perform file downloads in PHP with the file_get_contents() function.

The file_get_contents() function gets/downloads a file(locally or from the web) as a string. We can then modify the string and save it with file_put_contents().

Let’s see the example code below.

Code:

<?php

//For this example I will download the html of my blogs homepage. 
$url = "https://eecs.blog/";

//Get content as a string. You can get local content or download it from the web.
$downloadedFile = file_get_contents($url);

//Save content from string to .html file.
file_put_contents("downloadedWebPage.html", $downloadedFile);



//You can download an image as well ... or any other kind of file.
$downloadedFile = file_get_contents("https://eecs.blog/wp-content/uploads/2021/08/Code-Snippets-Force-File-Download-1024x576.png");
file_put_contents("downloadedImage.png", $downloadedFile);

Resulting Output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger