Solved

Accessing Zip Files Outside Public_HTML Folder

Posted on 2013-05-12
3
909 Views
Last Modified: 2013-05-12
I have a need to allow users to download ZIP files that reside outside the Public_HTML folder and found a PHP script that does just that - http://forums.phpfreaks.com/topic/129814-solved-accessing-images-and-files-that-are-located-outside-document-root/

It works great for PDF files but when I put a zip file in, the browser tries to save/open secure.php for some reason.  I shrunk the code down a bit as follow:

Link Page to download
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body >
<a href="secure.php?file=45int.zip">File Linke</a>
</body>
</html>

Open in new window


secure.php file:

<?php
  $folder = realpath('/home/rogersho/tester');
  $file = realpath($folder.'/'.$_GET['file']);
  header(sprintf("Content-type: %s;",getMimeType($file)));
  readfile($file);
  exit;

   function getMimeType ( $filename ) {
    //MIME MAP
$mime_extension_map = array(
    'pdf'           => 'application/pdf',
    'zip'           => 'application/zip'
);
    //Get Extension

    $ext = strtolower(substr($filename,strrpos($filename,'.') + 1));
    if(empty($ext))
      return 'application/octet-stream';
    elseif(isset($mime_extension_map[$ext]))
      return $mime_extension_map[$ext];
    return 'x-extension/' . $ext;
  }
?>

Open in new window

0
Comment
Question by:Jason92s
  • 2
3 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
Don't send the MIME type.  This is what I was trying to get across in the other question.  Install this script, put the name of your file in line 14, and run it.  If there is something you do not understand about it, please post back and I will try to help.

<?php // RAY_force_download.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/RAY_short_text_file.txt";

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


// 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)
    {
        // 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;
    }

    // ERROR
    else
    {
        trigger_error("ERROR: UNABLE TO OPEN $filename", E_USER_ERROR);
    }
}

Open in new window

0
 

Author Comment

by:Jason92s
Comment Utility
Oh, now I see what you're saying.  Perfect, works great, thank you.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Great!  Thanks for the points and good luck with the project, ~Ray
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
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…
The viewer will learn how to count occurrences of each item in an array.

743 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

15 Experts available now in Live!

Get 1:1 Help Now