Solved

Determine how long it takes to download

Posted on 2013-01-20
8
269 Views
Last Modified: 2013-02-03
hi guys,

i've recently inherited some php pages (running on an apache server) and unfortunately know very little about php. essentially one of the pages sends a file to the user in the form of:
		ob_start();	
		header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
		header("Cache-Control: no-cache, must-revalidate");
		header('Content-Type: application/octet-stream');
		header ('Location: ' .$expfilename);	
		ob_end_flush();

Open in new window


...or at least i expect this is some sort of php/html way to send data (although the "expires" part doesnt look right). my problem is that i've been asked to try and determine how long it takes for users to download these files and i have no idea how.

can anyone please point me in the right direction?
also is there a more efficient/cleaner/better way of sending files?

cheers
0
Comment
Question by:gem56
8 Comments
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 38799572
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");

Is one of the ways of indicating that the file should not be cached.

Is the measure of download a on time thing or do you need to keep stats over time?

Using ob_ prefixed functions is for output buffering and it is the right way to transfer the files under php control.

Cd&
0
 

Author Comment

by:gem56
ID: 38799588
hi COBOLdinosaur, thanks for your reply.

ahh ok, thanks for clarifying that.

the idea about the time thing is that our files are getting larger and larger and theres concerns that it may start taking longer than acceptable time for our users to be downloading these files, so we'd like to monitor that. unfortunately it seems as though none of us here know much about the web side of programming so the best idea that we can conceive is to someone track how long it takes for the user to download a file and then output it somewhere later on....so more or less to keep stats over time.

cheers
0
 
LVL 12

Expert Comment

by:sivagnanam chandrakanth
ID: 38799940
you can try something like this, I have tested its working

<?php
// gets the starting time
$time_start = microtime(true);

// gets the intro.mp3 file and outputs it to the user
$filename = "Wildlife.wmv";
header('Content-type: audio/mpeg');
header('Content-Length: '.filesize($filename));
header('Content-Disposition: attachment; filename="Wildlife.wmv"');
readfile($filename);

// gets the end time and duration
$time_end = microtime(true);

// write time to hdd, database, whatever
// ...
error_log("Processing time: ". sprintf("%.4f", ($time_end-$time_start))." seconds");
$con=mysql_connect("localhost","root","");
mysql_select_db("expert",$con);
$time=$time_end-$time_start;
mysql_query("INSERT INTO testdatabase values('".$time."')");
?>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 38801026
Wow, if you inherited a PHP web site and you don't know PHP, you have your work cut out for you!  Probably best to learn some foundation information about PHP before you start making changes to anything (And back all the scripts up).  This is a good introductory book.
http://www.sitepoint.com/books/phpmysql5/

And PHP has its own tutorial and online documentation.  Other good learning resources include W3Schools and Tizag.

The code posted with the original question sends some HTTP headers, the last of which redirects the client browser to an undefined variable.  Presumably this field is populated elsewhere, not showing in this code fragment.

You may be able to time the download successfully, but I am wondering what you can do with the resulting information?  All you will get is the time it took on the server, not an indication of the time experienced by the client.  The speed of the download is determined by many things that are outside or your script's control - the buffering on the server, the speed of the client internet connection, error handling and retry, etc.  So if you found that a message to me took 5 seconds and an identical message to my classroom took 12 seconds, what course of action would be indicated?  

In testing this script, I found that a file of 8,382,182 bytes took about 6 seconds as observed by watching my browser.  However the script reported as follows:
DOWNLOAD_TIME 0.010 SECONDS FOR GeoIPCountryWhois.csv

Conclusion: Timing the download by getting start and stop times for the PHP script may not give you enough information to be useful.  You should test this carefully in your own server to see if it can get meaningful results.

<?php // RAY_temp_gem56.php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('log_errors',     TRUE);


// DEMONSTRATE HOW TO CAUSE A FILE DOWNLOAD


// REQUIRED FOR USE WITH THE PHP date() FUNCTIONS
date_default_timezone_set('America/New_York');

// A FILE TO DOWNLOAD - THIS LINK COULD COME IN THE URL VIA $_GET, OR COULD BE GENERATED INSIDE THE SCRIPT
$url = "http://www.LAPRBass.com/GeoIPCountryWhois.csv";

// THE USE CASE FOR THE FUNCTION
$timex = force_download($url);

// RECORD THE TIME IT TOOK TO FORCE THE DOWNLOAD
$timer_msg = "DOWNLOAD_TIME $timex SECONDS FOR " . basename($url) . PHP_EOL;
file_put_contents('timer.txt', $timer_msg);


// FUNCTION TO FORCE A DOWNLOAD FROM A FILE
function force_download($filename)
{
    // GET THE CONTENTS OF THE FILE
    $filedata = file_get_contents($filename);

    // SUCCESS
    if ($filedata)
    {
        // TIMER
        $alpha = microtime(TRUE);

        // GET A NAME FOR THE FILE
        $basename = basename($filename);

        // THESE HEADERS ARE USED ON ALL BROWSERS
        header("Content-Type: application-x/force-download");
        header("Content-Disposition: attachment; filename=$basename");
        header("Content-length: ".(string)(strlen($filedata)));
        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");

        // THIS HEADER MUST BE OMITTED FOR IE 6+
        if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
        {
            header("Cache-Control: no-cache, must-revalidate");
        }

        // THIS IS THE LAST HEADER
        header("Pragma: no-cache");

        // FLUSH THE HEADERS TO THE BROWSER
        flush();

        // WRITE THE FILE
        echo $filedata;

        // TIMER IN SECONDS
        $omega = microtime(TRUE);
        return number_format($omega - $alpha, 3);
    }

    // ERROR
    else
    {
        die("ERROR: UNABLE TO OPEN $filename");
    }
}

Open in new window

Obviously, I am not willing to leave that script on my server, so if you want to experiment with it, please copy the code snippet and make your own tests.   Best regards, ~Ray
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:gem56
ID: 38849693
hi guys,

thank you for the replies and apologies for the severe delay, been buried with work.

@Ray_Paseur: thank you for that absolute wealth of information! ok so if i understand you correctly then theres no *real* or accurate way to determine how long the client experienced the download took? if thats the case am i better served perhaps putting a timestamp into a database when the client attempts to download, initiate the download, then when the download is complete on the client go to some dummy page which will timestamp the "download end time" ? ...or is there perhaps a better suited method?

cheers
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38849788
I think you're on the firmest ground that way.  After the server is done with the script it's out of your hands.  That's just the way HTTP client-server protocols work.
0
 

Author Comment

by:gem56
ID: 38849794
fair enough. guys thank you for your help, and Ray thanks for thoroughly explaining it all!

cheers mate
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38849818
Thanks for the points and thanks for using EE.  All the best, ~Ray
0

Featured Post

Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

746 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now