Solved

Download file progress percentage with PHP and AJAX

Posted on 2015-02-20
11
1,119 Views
Last Modified: 2015-02-20
Right now I have a test-functions.php page that contains a function that downloads a text file from an URL using PHP CURL. This curl call uses  CURLOPT_PROGRESSFUNCTION to call a function I made that writes progress to a text file. It does this by writing each number 1 to 100 with a new line for each entry (I have attached all the files below). What i now need help doing is modifying my javascript function on test.php to read the last line of the file, update at least every second (less time between updates would be great as well), and echo that line to the page. I then need it to stop when the value reaches 100 and display some new text.
test.php
test-functions.php
progress.txt
0
Comment
Question by:ITNC
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
  • 2
11 Comments
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 40621620
The general idea here is to use the javascript setInterval() to call a function every xxx number of milliseconds. Having a quick look at your code, I would advise that you don't write all the percentages to the progress.txt file - just write the current percentage. Simply change your fopen mode to w. This will make it easier to read in later.

$fp = fopen('progress.txt', 'w')

Open in new window

;

Now in your javascript, you'd do something like the following:

// declare this at the global level
var progressTimer;

// add this function
function getProgress() {
	$.get('progress.txt', function(data) {
		var percentage = parseInt(data);
		$('#response').html(percentage);
		if (percentage == 100) clearInterval(progressTimer);
	});
}

// when you start your AJAX request, add this:
progressTimer = setInterval(function() { getProgress() }, 1000);

Open in new window


One issue that I can see you having problems with is what happens if 10 people try to download the file at the same time - the progress.txt file won't be accurate at all.
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 40621643
The way around the multiple user problem would be to use individual files using the session for naming the file.  It will mean the javascript has to have the file name but it should not be difficult to implement.

Cd&
0
 

Author Comment

by:ITNC
ID: 40621645
I will start testing this now thank you. Luckily with our setup that will not be an issue but thanks for being thorough.
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 

Author Comment

by:ITNC
ID: 40621695
So what I am seeing after making these changes is that the file is read and the number 1 is displayed, it never updates after that on the screen. I check the progress file however and it shows 100 so I know the numbers are being written to the file. Just to be sure I download the progress file at random times after starting the transfer and I did in fact see different numbers.
0
 

Author Comment

by:ITNC
ID: 40621779
Now oddly during testing I see 100 displayed immediately even though the text file contains otherwise. Any ideas on what may be happening here?
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 40621807
The progress.txt file is probably being cached. If you switch your code to using the jQuery ajax() method, then you can prevent caching with the cache:false setting. Alternatively you can append a random string to the progress.txt file.. something like this

"progress.txt?" + Date().getTime()
0
 

Author Comment

by:ITNC
ID: 40621876
So I switched my code over (correctly I think but not completely sure) but I get the same result. Here is the call now:

function ajax_downloadTest() {
                $.ajax({
                    type: "POST",
                    url: "test-functions.php",
                    data: "mode=download",
                    cache:false
                });

            progressTimer = setInterval(function() { getProgress() }, 1000);
        }
0
 

Author Comment

by:ITNC
ID: 40621883
I should mention that I tried multiple browsers and another computer even but I get the same results.
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 40621894
There could also be timing issues the script may be running into resource limitation through the pipe if there is a download going on and if there is heavy activity on the server, the PHP script may be getting throttled.  Net result would be sporadic and the manifestation would be out of synch results.

Cd&
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 40621896
You've set the cache to false for the ajax call to test-functions. It's the ajax call to progress.txt that needs it setting. The get() method I showed you earlier is just a shortcut to an ajax method. To use the cache:false setting, you'll need to use the long-hand method:

function getProgress() {
   $.ajax({
      url: "progress.txt",
      cache:false
   })
   .done(function(data) {
      var percentage = parseInt(data);
      $('#response').html(percentage);
      if (percentage == 100) clearInterval(progressTimer);
   });
}

Open in new window


Alternatively, use the random querystring method I mentioned:

function getProgress() {
   var progressFile = "progress.txt?" + new Date().getTime();
   $.get(progressFile, function(data) {
      var percentage = parseInt(data);
      $('#response').html(percentage);
      if (percentage == 100) clearInterval(progressTimer);
   });
}

Open in new window


Edit: just added the new keyword to the Date() function
0
 

Author Comment

by:ITNC
ID: 40621922
Oh brilliant, sorry for the misunderstanding all is working properly now. Thank you so much!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article discusses how to implement server side field validation and display customized error messages to the client.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question