Ways to download a file using PHP

Categories: php

There are several ways to download a file using php to a local relative path on your server. I mostly prefer using copy() function.

<?php
    set_time_limit(0); //may need this, if file is of bigger size..
	$url = "http://www.anildewani.com/icons/image.png";
	$path = "temp/downloaded.png";
	copy($url,$path);
?>

Technically copy() command is nothing but an implicit combination of file_get_contents() and file_put_contents(). Imagine getting file data using file_get_contents() and storing that data using file_put_contents().

Or else, you can use php-curl which is a rather long way..but can be used as an alternative anyways.

<?php
    set_time_limit(0); //may need this, if file is of bigger size..
	$url = "http://www.anildewani.com/icons/image.png";
	$path = "temp/downloaded.png";

	/* gets the data from a URL */
	function download_file($url)
	{
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$file = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
	$data = download_file($url);
	file_put_contents($path, $data);
	echo "Downloaded!";
?>

There are even more alternative ways, you can use wget or curl commands with system() or exec() functions if you have a linux server

<?php
system('wget http://www.anildewani.com/image.jpg -O image.jpg');
?>
<?php
system('curl http://www.anildewani.com/image.jpg --O image.jpg');
?>

Hope it comes handy to you!

Tags: , ,
No Comments

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>