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.
<?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);