Showing posts with label download. Show all posts
Showing posts with label download. Show all posts

Friday, September 8, 2017

jQuery Detect when browser receives file download | Detecting the File Download Dialog In the Browser

Client Side:

<script src="./../jquery-2.1.4.js"></script>

<script type="text/javascript">
$(document).ready(function () {

var downloadToken = new Date().getTime();

$("button").click(function () {
    downloadToken = new Date().getTime();
    $("[name='downloadToken']").val(downloadToken);
    $("form").trigger("submit");
    timer();
});

function timer() {
    var attempts = 100; /* As you required */
    var downloadTimer = window.setInterval(function () {
        var token = getCookie("downloadToken");
        attempts--;

        if (token == downloadToken || attempts == 0) {
            $(".log").prepend("Browser received file from server<br/>");
            window.clearInterval(downloadTimer);
        }
        else {
            $(".log").prepend("Browser not received file from server yet<br/>");
        }
    }, 1000);
}

function parse(str) {
    var obj = {};
    var pairs = str.split(/ *; */);
    var pair;
    if ('' == pairs[0]) return obj;
    for (var i = 0; i < pairs.length; ++i) {
        pair = pairs[i].split('=');
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return obj;
}

function getCookie(name) {
    var parts = parse(document.cookie);
    return parts[name] === undefined ? null : parts[name];
}

});
</script>

<form action="download.php" method="post">
    <input type="hidden" name="downloadToken"/>
    <button type="button">Download</button>
    <div class="log"></div>
</form>

Server Side Script as of PHP:

<?php
$file_name = "download.zip";
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=download.zip');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));

// Sleep 5 seconds...
sleep(5);

// Cookie will be expire after 20 seconds...
setcookie("downloadToken", $_POST["downloadToken"], time() + 20, "");

ob_clean();
flush();
readfile($file_name);

Browser Screenshot:






Tuesday, January 31, 2017

How to download files from command line in Windows, like Wget

Create a file named 'Download_File.vbs' with following contents:


DownloadUrl = "http://ovh.net/files/10Mb.dat"
FileLocation = "Download.dat"

Wscript.Echo "Start Downloading"
Set ObjXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
ObjXMLHTTP.open "GET", DownloadUrl, false, "username", "password"
'http.setTimeouts 5000, 5000, 10000, 10000 'ms - resolve, connect, send, receive'
'http.setRequestHeader "Authorization", "Basic MY_AUTH_STRING"
ObjXMLHTTP.send()

If ObjXMLHTTP.Status = 200 Then
 Set ObjADOStream = CreateObject("ADODB.Stream")
 ObjADOStream.Open
 ObjADOStream.Type = 1
 'adTypeBinary

 ObjADOStream.Write ObjXMLHTTP.ResponseBody
 ObjADOStream.Position = 0
 'Set the stream position to the start

 Set ObjFSO = Createobject("Scripting.FileSystemObject")
 If ObjFSO.Fileexists(FileLocation) Then ObjFSO.DeleteFile FileLocation
 Set ObjFSO = Nothing

 ObjADOStream.SaveToFile FileLocation
 ObjADOStream.Close
 Set ObjADOStream = Nothing
 Wscript.Echo "Download Completed: " + FileLocation
Else
 Wscript.Echo "File Not Found"
End if

Set ObjXMLHTTP = Nothing

And create another file in the same folder named 'Download_Command.bat' with following contents & double click to download file from defined url:


@ECHO OFF
cscript.exe Download_File.vbs
pause
exit;           

Sunday, January 12, 2014

Using php download a temporary file


<?php
$dataArray = array(
    "name" => "Pritom K Mondal",
    "company" => "Some Company"
);
$tmpName = tempnam(sys_get_temp_dir(), 'data');

$tmpFile = fopen($tmpName, 'w');
fputcsv($tmpFile, $dataArray);

header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=download.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tmpName));

ob_clean();
flush();
readfile($tmpName);
unlink($tmpName);
?>

Monday, August 19, 2013

Downloading a Remote File With cURL and PHP

cURL is a great tool to help you connect to remote web sites, making it easy to post forms, retrieve web pages, or even to download files. In this PhpRiot Snippet I'll show you how you can download a file straight to disk using cURL.
Note: To simplify our key points in this article we don't perform any error checking on the cURL requests. You should always do so; the curl_getinfo function is extremely useful for this.
If you use basic options when executing a cURL request, the returned data will be output directly. If instead you want to assign the response to a PHP variable you would specify the CURLOPT_RETURNTRANSFER option.
You can then read the response and write it to disk, as shown in the following listing. The $path variable is the location on the server where you want to write the file.
Listing 1 Downloading a file and saving it with file_put_contents() (listing-1.php)
<?php 
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
 
    file_put_contents($path, $data);
?>
There is however a problem with this code. If the file you're downloading is quite large, the entire contents must be read into memory before being written to disk. Doing so can result in your script breaking down due to exceeding the memory limit.
Note: Even if your memory limit is set extremely high, you would be putting unnecessary strain on your server by reading in a large file straight to memory.
Therefore, you should let cURL do the hard work by passing to it a writable file stream. You can do this using the CURLOPT_FILE option.
Note: Because we'll be writing to a file you no longer specify the CURLOPT_RETURNTRANSFER option.
To do this you must first create a new file pointer using fopen(). Next we pass this file pointer to cURL and perform the request. Finally, we close the file pointer.
Listing 2 Using cURL to download straight to a file stream (listing-2.php)
<?php     
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $fp = fopen($path, 'w');
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
    fclose($fp);
?>
That's all there is to it. You can now download files without worrying about exceeding PHP's memory limit.

PHP Script to force download big files using chunk

<?php
$file 
dirname(__FILE__) . "/download_it.zip";
if (
file_exists($file)) {
    if (
FALSE !== ($handler fopen($file'r'))) {
        
header('Content-Description: File Transfer');
        
header('Content-Type: application/octet-stream');
        
header('Content-Disposition: attachment; filename=' basename($file));
        
header('Content-Transfer-Encoding: chunked'); //changed to chunked
        
header('Expires: 0');
        
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        
header('Pragma: public');
      
        
//Send the content in chunks
        
while (false !== ($chunk fread($handler4096))) {
            echo 
$chunk;
        }
    }
    exit;
}
echo 
"<h1>Content error</h1><p>The file does not exist!</p>";?>

Monday, April 29, 2013

Create and download csv file from array using php


Create and download csv file from array using php.
<?php
function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $outputString = "";
    foreach($fields as $tempFields) {
        $output = array();
        foreach ( $tempFields as $field ) {
            if ($field === null && $nullToMysqlNull) {
                $output[] = "NULL";
                continue;
            }

            // Enclose fields containing $delimiter, $enclosure or whitespace
            if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
                $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
            }
            else {
                $output[] = $field;
            }
        }
        $outputString .= implode( $delimiter, $output )."\n";
    }
    return $outputString;
}
?>
Use:
<?php
$dataArray = array();
array_push($dataArray, array(
    "First Name",
    "Last Name",
    "Number",
    "Group"
));
foreach($dataList as $index => $data) {
    array_push($dataArray, array(
        "".$data["first_name"],
        "".$data["last_name"],
        "".$data["mobile_number"],
        "".$data["group_name"]
    ));
}
$csvString = arrayToCsv($dataArray);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=list.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $csvString;
?>

Thursday, April 4, 2013

Enabling Pspell for PHP in XAMPP on Windows

PHP provides spell checking functionality through the Pspell extension. Despite its name, the extension uses the Aspell library, as development of the Pspell library ceased in 2001. Being part of the GNU Project, Aspell is part of most Linux distributions but is not supplied with Windows. This page explains how to install Aspell and enable the Pspell extension in XAMPP on Windows.

Downloading and installing Aspell

A Windows port of Aspell is available on the Aspell website. The Windows port has not been updated in several years, but still functions on recent version of Windows.
First, download and run the ‘full installer’, which installs the library itself. Then download and install at least one language’s dictionary from the same page.

Copying the library DLL

While the PHP manual states that the Aspell DLL must be available within the Windows system path, under XAMPP it must be available in Apache’s ‘bin’ directory. Find the file aspell-15.dll, which by default is installed at C:\Program Files\Aspell\bin\aspell-15.dll, and copy it to the Apache ‘bin’ directory, which by default resides at C:\xampp\apache\bin.

Enabling the Pspell extension

To enable the Pspell extension, first find the php.ini file, which, depending on the XAMPP version, is by default located at either C:\xampp\apache\bin\php.ini or C:\xampp\php\php.ini. Open it in a text editor, find the following line (which should be in a block relating to extensions about halfway down the file), and remove the semicolon:
;extension=php_pspell.dll
If the line above wasn’t present in the file, add the following line:
extension=php_pspell.dll
Finally, enable the extension by restarting Apache using the XAMPP control panel.