MOCKSTACKS
EN
Questions And Answers

More Tutorials




How to download a file from a URL in PHP?


php file download from url

This example illustrates the use of file_get_contents() function to read the file into a string.

<?php

	// Initialize a file URL to the variable
	$url =
	'https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png';
	
	// Use basename() function to return the base name of file
	$file_name = basename($url);
	
	// Use file_get_contents() function to get the file
	// from url and use file_put_contents() function to
	// save the file by using base name
	if (file_put_contents($file_name, file_get_contents($url)))
	{
		echo "File downloaded successfully";
	}
	else
	{
		echo "File downloading failed.";
	}
?>

Output


After running the program:


Output


This example illustrates the use of the PHP Curl to make HTTP requests in PHP, in order to download the file.

<?php
// Initialize a file URL to the variable
$url =
'https://media.geeksforgeeks.org/wp-content/uploads/gfg-40.png';

// Initialize the cURL session
$ch = curl_init($url);

// Initialize directory name where
// file will be save
$dir = './';

// Use basename() function to return
// the base name of file
$file_name = basename($url);

// Save file into file location
$save_file_loc = $dir . $file_name;

// Open file
$fp = fopen($save_file_loc, 'wb');

// It set an option for a cURL transfer
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

// Perform a cURL session
curl_exec($ch);

// Closes a cURL session and frees all resources
curl_close($ch);

// Close file
fclose($fp);
?>

Output



Conclusion

In this page (written and validated by ) you learned about . What's Next? If you are interested in completing PHP tutorial, we encourage you simply to start here: PHP Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.