The below .php script doesn't work for me - it just prints jibberish:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/rapcDemo/documents/";
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
?>
Any ideas what I am doing wrong?
Well... This is the script I use. Maybe it will help.
Main donwload script:
<?php
$path = $_SERVER['DOCUMENT_ROOT']."/rapcDemo/documents/";
$fullPath = $path.$_GET['download_file'];
if(is_file($fullPath)) {
# required for IE
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
# get the file mime type using custom function
$mime = ($try = get_mime($fullPath)) ? $try : "application/octet-stream";
# set headers for download
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($fullPath)) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="' . $_GET['download_file']. '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($fullPath)); // provide file size
header('Connection: close');
readfile($fullPath); // push it out
exit();
}
?>
And this is my get_mime() function:
<?php
function get_mime($url = "") {
if (empty($url))
return FALSE;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$results = explode("\n", trim(curl_exec($ch)));
foreach ($results as $line)
if (strtok($line, ':') == 'Content-Type')
return trim(explode(":", $line)[1]);
return FALSE;
}
?>
Ok! I just found and modified a php script online that works like a charm:)
The link is below:
http://phpsnips.com/579/PHP-download-script-for-Large-File-Downloads
Related
guys.
I am using a local server with laravel framework and trying to download file.
I tried many cases but nothing works for me.
The thing is I get no errors.
Downloading wont`t start but in response I have something like this:
�
���JFIF��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 95��C
���}!1AQa"q2���#B��R��$3br�
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
���w!1AQaq"2�B���� #3R�br�
$4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������?���!�A���I��+�P�sB���i��?�Y�L��iG���B���Ap�����J;���;}ic=F{R�Z��
�$��z�q��~�p8�h�v?A#��;����t�#�Fx��Ǯq�S#<������qS-
That what I used:
tried this way:
$file = 'D:\Server\OpenServer\domains\memo.ru\public\img\avatars\\'.$file_name;
$filePath=$file;
and this:
$file = "http://example.com/img/avatars/1457091259.png";
1.
set_time_limit(0);
$file = #fopen($filePath, 'rb');
while ( !feof($file) ) {
print( #fread($file,1024*8) );
//ob_flush();
flush();
}
2
$handle = fopen($filePath, 'rb');
$buffer = '';
while ( !feof($handle) ) {
$buffer = fread($handle, 4096);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);
3
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
//header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
4
$real_path = 'D:\Server\OpenServer\domains\example.com\public\img\avatars\\';
$file = "http://example.com/img/avatars/1457091259.png";
$url = 'http://example.com/img/avatars/'.$tmpFileName;
$path = $real_path.$tmpFileName;
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
If you're using Laravel 5 then this would be the most straightforward way:
public function download()
{
$file = base_path(). "public/img/avatars/1457091259.png";
$name = "Human Name For File.jpg";
$headers = ['Content-Type: application/octet-stream'];
return Response::download($file, $name, $headers);
}
Just name sure you have use Response at the top before the class
The application/octet-stream header should force the browser to download the file rather than display it in the browser window.
This should work
header('Content-Type: image/png');
header('Content-disposition: attachment; filename='.$fileName);
echo readfile($file);
die();
I have used the following quite successfully for downloading / sending files - perhaps it will be of use to you?
Call it like:
call_user_func( 'send_file', 'myfile.docx', 'c:/temp/document.docx' );
function send_file( $name, $strPath ) {
if( file_exists( $strPath ) ) {
if( !is_file( $strPath ) or connection_status()!=0 ) { return FALSE; }
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Content-Type: application/octet-stream");
header("Content-Length: ".(string)( filesize( $strPath ) ) );
header("Content-Disposition: inline; filename={$name}");
header("Content-Transfer-Encoding: binary\n");
if( $file = fopen( $strPath, 'rb' ) ) {
while( !feof( $file ) and ( connection_status()==0 ) ) {
print( fread( $file, 1024*8 ) );
flush();
}
fclose( $file );
}
clearstatcache();
return( ( connection_status()==0 ) and !connection_aborted() );
}
}
I am unable to set proper headers to download file from URL.
Below code just shows content of URL in browser instead download.
$file_name = "image1.jpg";
$content_type = "image/jpeg";
$url = "http://ctan.imsc.res.in/macros/latex/contrib/incgraph/example.jpg";
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
header('Cache-Control: private',false);
header("Content-type: ".$content_type);
header("Cache-Control: no-store, no-cache");
header("Content-disposition: attachment; filename=".$file_name);
header("Location: ".$url);
exit(0);
Thanks in Advance.
$originalPath = $_REQUEST['path']; //path with filename
$fileName = $_REQUEST['fileName']; // filename for downloaded file name
if (file_exists($originalPath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($originalPath));
ob_clean();
flush();
readfile($originalPath);
exit;
} else {
echo 'FILE_NOT_FOUND';
}
using this code you can save image in our server and you can download image using my upper code.
file_put_contents("Tmpfile.jpg", fopen("http://ctan.imsc.res.in/macros/latex/contrib/incgraph/example.jpg", 'r'));
this code is work fine to download from url :
set_time_limit(0);
//File to save the contents to
$fp = fopen ('file.type', 'w+');
$url = "http://yoursite.come/file.type";
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);//get curl response
//done
curl_close($ch);
?>
Download file from url(in list) and save the file with last name of the url using python
import urllib.request as urllib2
import re,os
for url in open('C:\\Users\\SRINU\\Desktop\\Election_pdfs_urls\\33.txt'):
possible_urls = re.findall(r'(https?://[^\s]+)', url)
for links in possible_urls:
response = urllib2.urlopen(links.format(url.encode('utf-8')))
filename_w_ext = os.path.basename(links)
file = open(filename_w_ext, 'wb')
file.write(response.read())
file.close()
File uploaded will be store in database and folder (folder name: uploads).Now I want to know how to create download file from database/folder. I have two file butangDonload.php and download.php. When user click word "donload" the pop up box will appear and save the file.
butangDonload.php
<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."'>donload</a> ";
?>
download.php
<?php
$name= $_GET['nama'];
download($name);
function download($name) {
$file = $nama_fail;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
?>
I have changed to your code with little modification will works well.
Here is the code:
butangDonload.php
<?php
$file = "logo_ldg.png"; //Let say If I put the file name Bang.png
echo "<a href='download1.php?nama=".$file."'>download</a> ";
?>
download.php
<?php
$name= $_GET['nama'];
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name));
ob_clean();
flush();
readfile("your_file_path/".$name); //showing the path to the server where the file is to be download
exit;
?>
Here you need to show the path from where the file to be download.
i.e. will just give the file name but need to give the file path for reading that file. So, it should be replaced by
I have tested by using your code and modifying also will works.
here is the code to download file with how much % it is downloaded
<?php
$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );
curl_exec($ch);
curl_close($ch);
function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {
if($download_size!=0){
$percen= (($downloaded_size/$download_size)*100);
echo $percen."<br>";
}
}
?>
You can use html5 tag to download the image directly
<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>
For more information, check this link
http://www.w3schools.com/tags/att_a_download.asp
butangDonload.php
$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;
Try this,
<?php
$name=$_SESSION['name'];
download($name);
function download($name){
$file = $nama_fail;
?>
You can also use the following code:
<?php
$filename = $_GET["nama"];
$contenttype = "application/force-download";
header("Content-Type: " . $contenttype);
header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");
readfile("your file uploaded path".$filename);
exit();
?>
function downloadFiles($dir, $file) {
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="' . $dir . $file . '"');
header("Content-Transfer-Encoding: Binary");
header("Content-length: " . filesize($dir . $file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file . '"');
readfile("$dir$file");
}
$dir = "folder_path";
$file = "image_name.jpg";
$download = downloadFiles($dir,$file);
Try this way, it is helpful for me.
I would need to set the download status to 0 when download has finished. I am using x-sendfile, but after finish download, dont set status.
My code:
header("X-Sendfile: $file");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . $name . '"');
mysql_query("UPDATE `downloads` SET `download_status` = '1' WHERE `id` = '" . $last_down . "'");
Thanks for help
You can't detect when the client finished downloading the file if you using X-Sendfile.
Simplest way is stream file by script.
$handle = fopen($filepath, 'rb');
if ($handle !== false) {
#flock($handle, LOCK_SH);
$size = filesize($filepath);
$filename = basename($filepath);
$old_max_execution_time = ini_get('max_execution_time');
ini_set('max_execution_time', 0);
$old_cache_limiter = session_cache_limiter();
session_cache_limiter(false);
if (ob_get_length()) ob_clean();
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-disposition: attachment; filename="'. $filename .'"');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Accept-Ranges: bytes');
header('Cache-control: private');
header('Pragma: private');
set_time_limit(0);
while (! feof($handle) && (connection_status() === 0)) {
if (! $buffer = #fread($handle, $interval)) {
// Error
exit;
}
print($buffer);
flush();
}
#flock($handle, LOCK_UN);
#fclose($handle);
ini_set('max_execution_time', $old_max_execution_time);
session_cache_limiter($old_cache_limiter);
// ----------------------------------------------------
// Downloading complete!
// Here you can update your table row in DB...
// ----------------------------------------------------
exit;
}
I have created a YouTube search engine + download + MP3 convert script. I have used Jeckman's YouTube Downloader for creating this script. Everything is OK, except, I want to download the video into the server instead it downloading it to my computer. I want to do this because, after it gets download, I shall convert the video to MP3 using FFmpeg.
Is there any way to get the video downloaded in my server instead of my computer?
The download.php contains the following code:
<?php
// Check download token
if (empty($_GET['mime']) OR empty($_GET['token']))
{
exit('Invalid download token 8{');
}
// Set operation params
$mime = filter_var($_GET['mime']);
$ext = str_replace(array('/', 'x-'), '', strstr($mime, '/'));
$url = base64_decode(filter_var($_GET['token']));
$name = urldecode($_GET['title']). '.' .$ext;
// Fetch and serve
if ($url)
{
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE)
{
header('Content-Type: "' . $mime . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
}
else
{
header('Content-Type: "' . $mime . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
}
readfile($url);
exit;
}
// Not found
exit('File not found 8{');
?>
I've found out a solution to store the YouTube file to server. I have removed the header stuff and put $download_video_file = file_put_contents($file_path, fopen($url, 'r')); in place of readfile($url); and it worked like a magic! ^_^
Here's the complete code:
<?php
// Check download token
if (empty($_GET['mime']) OR empty($_GET['token']))
{
exit('Invalid download token 8{');
}
// Set operation params
$mime = filter_var($_GET['mime']);
$ext = str_replace(array('/', 'x-'), '', strstr($mime, '/'));
$url = base64_decode(filter_var($_GET['token']));
$name = urldecode($_GET['title']). '.' .$ext;
// Fetch and serve
if ($url)
{
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE)
{/*
header('Content-Type: "' . $mime . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
*/}
else
{/*
header('Content-Type: "' . $mime . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
*/}
$download_video_file = file_put_contents($file_path, fopen($url, 'r'));
exit;
}
// Not found
exit('File not found 8{');
?>