Truemag

  • Categories
    • Tips And Tricks
    • Internet
    • PHP
    • Javascript
    • CSharp
    • SQL Server
    • Linux
  • Lastest Videos
  • Our Demos
  • About
  • Contact
  • Home
  • Write With Us
  • Job Request
Home PHP PHP Download Image Or File From URL

PHP Download Image Or File From URL

I’ll show you 3 php functions that download a particular file (ex: image,video,zip,pdf,doc,xls,etc) from a remote resource (via a valid URL) then save to your server.

Depending on your current php.ini settings, some functions may not work; therefore, let try which function is best for you.

Note: please ensure the folder you want to store the downloaded file is existed and has write permission for everyone or the web process.

Download file from URL with PHP

For all examples below, I assume that we’re going to download a remote image from URL: http://4rapiddev.com/wp-includes/images/logo.jpg and save it to a download sub folder with name: file.jpg.

1. PHP Download Remote File From URL With file_get_contents and file_put_contents

<?php
	function download_remote_file($file_url, $save_to)
	{
		$content = file_get_contents($file_url);
		file_put_contents($save_to, $content);
	}
?>

Example:

<?php
	download_remote_file('http://4rapiddev.com/wp-includes/images/logo.jpg', realpath("./downloads") . '/file.jpg');
?>

2. PHP Download Remote File From URL With CURL

<?php
	function download_remote_file_with_curl($file_url, $save_to)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 0); 
		curl_setopt($ch,CURLOPT_URL,$file_url); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		$file_content = curl_exec($ch);
		curl_close($ch);
 
		$downloaded_file = fopen($save_to, 'w');
		fwrite($downloaded_file, $file_content);
		fclose($downloaded_file);
 
	}
?>

Example:

<?php
	download_remote_file_with_curl('http://4rapiddev.com/wp-includes/images/logo.jpg', realpath("./downloads") . '/file.jpg');
?>

3. PHP Download Remote File From URL With fopen

<?php
	function download_remote_file_with_fopen($file_url, $save_to)
	{
		$in=    fopen($file_url, "rb");
		$out=   fopen($save_to, "wb");
 
		while ($chunk = fread($in,8192))
		{
			fwrite($out, $chunk, 8192);
		}
 
		fclose($in);
		fclose($out);
	}
?>

Example:

<?php
	download_remote_file_with_fopen('http://4rapiddev.com/wp-includes/images/logo.jpg', realpath("./downloads") . '/file.jpg');
?>

Again, “download” folder must be exists and writable.

Aug 31, 2011 Hoan Huynh
How To Save PHP Error Log To File In IISFree Cloud Server For Testing
You Might Also Like:
  • ASP.Net C# Download Or Save Image File From URL
  • PHP Save String Content To File
  • Get File Mime Type Using PHP
  • PHP Read File Using Fread() Simple Example
  • View Download List In Google Chrome And Firefox
  • PHP Get Remote Image Width Height
  • PHP Delete File Function
  • PHP Get Image Width And Height
  • Manage MacBook Hosts File Easier With Hosts Widget
  • FancyBox Redirect To A Predefined URL When Click On Image
  • http://www.herculessport.com India Sports

    This is very great information about this articles..this is very informative post..

  • Pingback: PHP Get Image Width And Height | 4 Rapid Development()

  • http://www.google.com/ Evaline

    Gee wliilkres, that’s such a great post!

    • mladen

      I dont understand what exactly input in “$save_to” Here I try this:
      where is error?

  • mladen

    I dont understand what exactly input in “$save_to” Here I try this:
    where is error?

    thanx

    • hoanhuynh

      Hi mladen, you need to pass a real location to save the image on your server/computer to $save_to parameter, ex: D:/htdocs/download/file.jpg

  • mladen

    Ill replace β€œ$save_to” with my link to folder on my server betwen ‘ ‘
    ‘http://www.c-bit.hr/1/ASBIS/download/’
    and download folder have permision 777
    file url is replaced with ‘http://cdn2.4rapiddev.com/wp-includes/images/logo.jpg’
    no result

    • hoanhuynh

      Hi,it shoud be a phiscical path on your server,not url path. Hope it helps. H2

  • mladen

    Thanx for answer
    but I dont know this path,, My directory “sranje” is in public_html folder and “skidaj.php” is also in public_html what is phisical path in my case
    (‘http://cdn2.4rapiddev.com/wp-includes/images/logo.jpg’, ‘./home/cbithr/public_html/sranje’ )
    Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘&’ or T_VARIABLE in /home/cbithr/public_html/skidaj.php on line 2

    should I replace $content with name of image or what ? Im talking about first example

    • hoanhuynh

      Dear mladen,

      Let’s try with this:

      download_remote_file(‘http://cdn2.4rapiddev.com/wp-includes/images/logo.jpg’, ‘/home/cbithr/public_html/sranje/download/file.jpg’);

      … and also make sure you already added the function definition.

      Good luck,
      H2.

      • mladen

        Thanx hoanhuynh now works.
        In case a got several link and want to download all links(pictures.jpg) in one folder with existing names
        how to define $save_to link in this case ?
        Ill try replace $save_to with folder path but without result
        /home/cbithr/public_html/sranje/download/

  • mladen

    works with PHP Download Remote File With fopen
    /home/cbithr/public_html/sranje/download/.$name_of_string
    Thanx

  • Greg Newman

    Nice post – a quick additional related question: What can one do when the $file_url is not fully qualified and does not directly point to a file.zip but rather points to a page that itself forces download of a file.zip. My example URL is:

    http://ge.ssec.wisc.edu/modis-today/index.php?gis=true&filename=t1_12019_USA2_143_250m&date=2012_01_19_019&product=true_color&resolution=250m&overlay_sector=false&overlay_state=true&overlay_coastline=true

    Any help greatly approeciated!

    • hoanhuynh

      Hi Greg Newman,

      Thanks for your good question, below is a answer for your question:

      1. Download that file and name it whatever you want, for example: file.jpg. I tried with PHP CURL, option 2.

      2. Use PHP function: mime_content_type to determine its mine type.

      ———————
      echo mime_content_type(realpath(“./downloads”) . ‘/file.jpg’); //return: application/zip in this case
      ———————

      3. Base on its mine type, use another PHP function to rename it to a corresponding extension (zip).

      Hope it’s clear.

      H2.

  • Greg Newman

    Forgot to check Notify Me.

    • hoanhuynh

      Me again πŸ˜‰

      Don’t understand your comment.

      H2.

      • Greg Newman

        Hi H2,

        Thanks for your insight (a[pologies for my cryptic second post). I’ll try as you suggest, using PHP CURL Option 2 to download the file. It is at this step that I think I am having trouble… is there specific header declarations that will be important for option 2 to force a download of the file from the webiste I listed?

        Again – thank you! More soon, Greg

  • Noemail

    Great! Thanks!Β 

  • Emraan Rehman

    Itz very Helpfull, Thank guys. Allah Bless u.

  • jiiva

    i cant understood this function , plz help me to send full coding with procedure

  • http://gencprogramci.net Windofelm

    Thanks a lot ..

  • Paras

    it’s store file with 0 bytes not download image please give me solution.

Hoan Huynh

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com

Link6 years ago PHPcURL, file_get_contents, file_put_contents, fopen, Fread, fwrite14,301
0
GooglePlus
0
Facebook
0
Twitter
0
Digg
0
Delicious
0
Stumbleupon
0
Linkedin
0
Pinterest
Most Viewed
PHP Download Image Or File From URL
14,301 views
Notepad Plus Plus Compare Plugin
How To Install Compare Text Plugin In Notepad Plus Plus
10,259 views
Microsoft SQL Server 2008 Attach Remove Log
Delete, Shrink, Eliminate Transaction Log .LDF File
10,259 views
JQuery Allow only numeric characters or only alphabet characters in textbox
8,977 views
Firefox Can Not Connect To Proxy Server
Fix Can Not Connect To Proxy Server In Firefox, Google Chrome And Internet Explorer
5,869 views
4 Rapid Development is a central page that is targeted at newbie and professional programmers, database administrators, system admin, web masters and bloggers.
Recent Posts
  • Magento Fatal error: Unsupported operand types
  • Ionic bower the name contains uppercase letters
  • PHP Magento Get Manufacturer Name And ID From Magento Product ID
  • Know Simple Hacks To Systematize Media Library in WordPress
  • A handy guideline on adding custom menu item in WordPress admin
Categories
  • CSharp (45)
  • Facebook Graph API (19)
  • Google API (7)
  • Internet (87)
  • iPhone XCode (8)
  • Javascript (35)
  • Linux (26)
  • MySQL (16)
  • PHP (84)
  • Problem Issue Error (29)
  • Resources (32)
  • SQL Server (25)
  • Timeline (5)
  • Tips And Tricks (140)
EMAIL SUBSCRIPTION

Sign up for our newsletter to receive the latest news and event postings.

Recommended
  • CDN
  • Hosting
  • Premium Themes
  • VPS
2014 © 4 Rapid Development