Jump to content

Download file through php


marklarah

Recommended Posts

well I have this

 

header("Content-Type: application/octet-stream;");
header('Content-Disposition: attachment; filename="'.$name.'"');
$curl_handler = curl_init();
curl_setopt($curl_handler, CURLOPT_URL, $url);
curl_setopt($curl_handler, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($curl_handler, CURLOPT_BINARYTRANSFER, 1); 
//$data = curl_getinfo($curl_handler, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_exec($curl_handler);
curl_close($curl_handler);
exit;

This could use some better error handling, and if I sat here and thought about it, I could probably optimize it some, but:

 

<?php

define('BUFFER_SIZE', 8192);
define('ALERT_SIZE', 1024); //alert each KB

$sock = fsockopen('localhost', 80);

$headers = "GET /somefile.php HTTP/1.1
Host: localhost
Connection: close
\r\n";

$hl = strlen($headers);

if(fwrite($sock, $headers) == $hl) {
//All content was written successfully.
$content = $line = '';
//First get the headers using fgets.
$length = -1;
while(!feof($sock)) {
	$line = trim(fgets($sock));
	if(empty($line))
		break;
	if(stripos('Content-Length:', $line)) {
		//Woo, there's a content-length header.
		$length = preg_replace('~[^0-9]~', '', $line);
	}
}

//Done with headers....  Get content now.
if($length != 0) {
	//Uhmm... if length is 0, that means that Content-Length: 0 was sent, in which case, there is not content.
	$size_so_far = 0; //number of bytes downloaded.
	$len = ($length > 0) ? $length : 'N/A';
	$factor = 0; //No better name for this x.x.
	while(!feof($sock)) {
		$tmp = stream_get_contents($sock, BUFFER_SIZE);
		$content .= $tmp;
		$size_so_far += strlen($tmp);
		if($length != -1 && $size_so_far == $length)
			break;
		if(floor($size_so_far/ALERT_SIZE) > $factor) {
			$factor = floor($size_so_far/ALERT_SIZE);
			$bytes = $factor*ALERT_SIZE; //yeah, this could be wrong, but it will look prettier ;p.
			echo "{$bytes} bytes downloaded of {$len} bytes.\n";
		}
	}
	echo "Done downloading {$size_so_far} bytes.\n";
}

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.