5

End goal: Click link on page 1, end up with file downloaded and refresh page 1. Using PHP to serve downloads that are not in public html.

Approach:

Page 1. Link transfers to page 2 with get variable reference of which file I am working with.

Page 2. Updates relevant SQL databases with information that needs to be updated before refresh of page 1. Set "firstpass" session variable. Set session variable "getvariablereference" from get variable. Redirect to page 1.

Page 1. If first pass session variable set. Set Second pass session variable. Unset first pass variable. Refresh Page. On reload the page will rebuild using updated SQL database info (changed on page 2.).

Refreshed Page 1. If second pass session variable set. Run download serving header sequence.

This is page 1. I am not showing the part of page 1 that has the initial link. Since it doesn't matter.

// REFERSH IF FIRSTPASS IS LIVE
if ($_SESSION["PASS1"] == "YES"){
    $_SESSION["PASS1"] = "no";
    $_SESSION["PASS2"] = "YES";
    echo "<script>document.location.reload();</script>";
    }
if ($_SESSION["PASS2"] == "YES"){
    // Grab reference data from session:
        $id = $_SESSION['passreference'];
                // Serve the file download
                        //First find the file location
                        $query = "SELECT * from rightplace
                              WHERE id = '$id'";
                        $result = mysql_query($query);
                        $row = mysql_fetch_array($result);
                        $filename = $row['file'];
                        $uploader = $row['uploader'];   
                            // Setting up download variables
                                $string1 = "/home/domain/aboveroot/";
                                $string2 = $uploader;
                                $string3 = '/';
                                $string4 = $filename;
                                $file= $string1.$string2.$string3.$string4;
                                $ext = strtolower (end(explode('.', $filename)));
                                //Finding MIME type
                                    if($ext == "pdf" && file_exists($file)) {
                                        header("Content-disposition: attachment; filename= '$filename'");
                                        header('Content-type: application/pdf');
                                        readfile($file);
                                        }                                   
                                    if($ext == "doc" && file_exists($file)) {
                                        header("Content-disposition: attachment; filename= '$filename'");
                                        header('Content-type: application/msword');
                                        readfile($file);
                                        }                   
                                    if($ext == "txt" && file_exists($file)) {
                                        header("Content-disposition: attachment; filename= '$filename'");
                                        header('Content-type: text/plain');
                                        readfile($file);
                                        }                   
                                    if($ext == "rtf" && file_exists($file)) {
                                        header("Content-disposition: attachment; filename= '$filename'");
                                        header('Content-type: application/rtf');
                                        readfile($file);
                                        }
                                    if($ext == "docx" && file_exists($file)) {
                                        header("Content-disposition: attachment; filename= '$filename'");
                                        header('Content-type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
                                        readfile($file);
                                        }
                                    if($ext == "pptx" && file_exists($file)) {
                                        header("Content-disposition: attachment; filename= '$filename'");
                                        header('Content-type: application/vnd.openxmlformats-officedocument.presentationml.presentation');
                                        readfile($file);
                                        }
                                    if($ext == "ppt" && file_exists($file)) {
                                        header("Content-disposition: attachment; filename= '$filename'");
                                        header('Content-type: application/vnd.ms-powerpoint');
                                        readfile($file);
                                        }
                                        }

The script on page 2 is working correctly. It updates the sql database and redirects to the main page properly. I have also checked that it sets the "$_SESSION['passreference'];" correctly and nothing on page 1 would unset it.

So, thats the whole long explanation of the situation. I am stumped. What happens is, as I said page 2 works fine. Then it kicks to page 1, refreshes and then doesnt push any download. I know that the download script works and that the files are there to be downloaded (checked without the whole refresh sequence).

I essentially have two questions:

  1. Can anyone spot whats going wrong?

  2. Can anyone conceptualize a better approach?

user187680
  • 657
  • 1
  • 6
  • 19
  • 1
    Start to learn about subroutines, in PHP those are called functions. That should help you a lot to better approach this (and many other) programming problems. They help, too, with debugging, so you should be better able to spot what's wrong. – hakre Aug 08 '12 at 01:15
  • Does it matter if the user clicks `Cancel`? – uınbɐɥs Aug 13 '12 at 03:55
  • Isn't it : `window.location.reload()` instead of `document.location.reload()` ? – javascript is future Aug 13 '12 at 16:43

3 Answers3

6

It is hard to debug something like this remotely even given the code, the segment you posted works as you say. Have you checked your error logs? The most likely culprit is a problem with sending header() after other output has been done.

When dealing with file downloads, I think it is easier wherever possibly to initiate the download on a new page/window so there can be no risk of breaking headers. Maybe a slightly altered sequence using a third page that initiates the actual download:

  1. Page 1 links to the second page to do magic, which redirects back to page 1
  2. Page 1 then spawns page 3 in a new window, which initiates the download.

There's a good example code for loading a new window for a download in this answer.

Community
  • 1
  • 1
John C
  • 7,805
  • 2
  • 35
  • 46
3

Looking at your code, the download problem may be that the $ext variable contains an unexpected value or that the $file variable contains the name of a file that really doesn't exist.
In either this cases, none of your "if" conditions would be true, so the download would'nt start.
My suggestion is to add the following statements just before the "//Finding MIME type" comment line:

$log  = "file='".$file."'\n";
$log .= "ext='".$ext."'\n";
@file_put_contents("/tmp/page1.log", $log, FILE_APPEND);

This way, looking at the "/tmp/page1.log" file you should be able to check if the $file and $ext variabiles effectively contain the expected values.
I've used "/tmp/page1.log" as the log file name since I suppose that you're working on linux; if not, please adjust the first argument of the "file_put_contents" function with a valid path and file name for your enviroment.
Also, I would replace the sequence of "if" tests with the following code:

$content_types = array(
    "pdf"  => "application/pdf",
    "doc"  => "application/msword",
    "txt"  => "text/plain",
    "rtf"  => "application/rtf",
    "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation"
);

if (isset($content_types[$ext])) {
    if (file_exists($file)) {
        header("Content-disposition: attachment; filename= '$filename'");
        header('Content-type: '.$content_types[$ext]);
        readfile($file);
        die("");
    } else {
        die("** '".$file."' does not exist **");
    }
} else {
    die("** Unhandled '".$ext."' extension **");
}

Obviously, you should implement the error handling in a much more robust way, not simply using the "die()" function as I did, but this is only an example.
Finally, be aware that there are also better ways of getting the content-type corresponding to the file extension; for example one solution is to use the PHP Fileinfo functions.
Have a look at this answer for further information about this topic.
Keep also in mind that in safe mode the file_exists function always returns FALSE, and that the results of the file_exists function are cached; see the clearstatcache() function on the PHP manual for further details.

Community
  • 1
  • 1
0

I just reworked your PHP code a bit. Especially you'll get more information about what's going wrong. Just try this code and read the following comments, which explain what happend, if you get one of the new error messages. Also read the NOTE part below, which explains why you probably can't access a file from PHP, even it's existing and is in the right directory.

  1. Using window.location.reload(); instead of document.location...
  2. I added an error()-function. You can add more HTML to it, so it's producing a page in the layout you want. And you could log the error to a local file, too. There is a private info parameter used to pass sensible information as database errors (can contain SQL) to the function. For productive use you shouldn't display that to the user. Instead you can log it into a file or only display it for privileged users (e.g. Administrators).
  3. Checks weather $id is set. Returns error() message if not; Could happen if session was not updated correctly.
  4. I added "$id = addslashes($id);" for security reasons. If your id could be set to values like $id = "' OR 1" (SQL-Injection) for example, you could get into trouble. If you are sure this can not happen, you can remove it.
  5. It checks the $result variable after the DB query. If e.g. your database connection wasn't established or the script cannot connect this will produce an error()-output that informs you. The same happens if you have an error in your SQL syntax, e.g. wrong table name.
  6. It's also checked weather a valid $row is fetched from the database. If there isn't a row returned your $id is problably wrong (there isn't such an entry in your database).
  7. I rewrote your string operations to $filepath = $rootpath . "/" . $uploader . "/" . $filename; where $rootpath is set before without "/" at the end; This is easier to read...
  8. Extensions and MIME-Types are now put into an array, instead of using a lot of "if-then"-blocks, that's easier to maintain. Also the code inside that blocks were similar... so we only need to write it once.
  9. A default MIME type (Content-Type:"application/octet-stream) is sent, if the file extension is not known.
  10. We check for file_exists() and output an error message, with $filename given to allow checking weather the path is correct...

So here is the source code:

<?php 

function error($message, $info = "") {
  echo "ERROR: $message<br>";
  echo "PRIVATE-INFO: $info"; // probably you only want to log that into a file?
  exit;
}

// REFERSH IF FIRSTPASS IS LIVE
if ($_SESSION["PASS1"] == "YES") {
  $_SESSION["PASS1"] = "no";
  $_SESSION["PASS2"] = "YES";
  echo "<script>window.location.reload();</script>";
  exit;
}


if ($_SESSION["PASS2"] == "YES") {
  // Grab reference data from session:
  $id = $_SESSION['passreference'];

  if (!$id) error("Internal Error ('id' not set)");

  // Select file location from DB
  $id = addslashes($id);
  $query = "SELECT * from rightplace WHERE id = '$id'";
  $result = mysql_query($query);

  if (!$result) error("DB-query execution error", mysql_error());

  $row = mysql_fetch_array($result);
  mysql_free_result($result);

  if (!$row) error("File with ID '$id' was not found in DB.");

  $filename = $row['file'];
  $uploader = $row['uploader'];

  // Setting up download variables
  $rootpath = "/home/domain/aboveroot";
  $filepath = $rootpath . "/" . $uploader . "/" . $filename;
  $ext = strtolower(end(explode('.', $filename)));

  // Serve the file download

  // List of known extensions and their MIME-types...
  $typelist = array(
      "pdf"  => "application/pdf",
      "doc"  => "application/msword",
      "txt"  => "text/plain",
      "rtf"  => "application/rtf",
      "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
      "ppt"  => "application/vnd.ms-powerpoint"
  );

  // set default content-type
  $type = "application/octet-stream";

  // for known extensions, assign specific content-type
  if (!isset($typelist[$ext])) $type = $typelist[$ext];

  if (file_exists($filepath)) {
    header("Content-disposition: attachment; filename= '$filename'");
    header("Content-type: $type");
    readfile($filepath);
  } else {
    error("Error: File '$filepath' was not found!", $filepath);
  }
}

?>

NOTES:

  1. The file not found error can happen even the file exists. If this happens, this is most probably a security mechanism that prevents the PHP script to access files outside the HTML-root directory. For example php scripts could be executed in a "chrooted" environment, where the root directory "/" is mapped e.g. to "/home/username/". So if you want to access "/home/username/dir/file" you would need to write "/dir/file" in your PHP script. It can be even worse, if your root is set like "/home/username/html"; then you'll not be able to access directories below your "html" directory. To work around that, you can create a directory inside the HTML-root and put a file named ".htaccess" there. Write "DENY FROM ALL" in it, which prevents access to the directory by browser request (only scripts can access it). This works for apache servers only. But there are solutions like that for other server software too... More info on this can be found under: http://www.php.net/manual/en/ini.core.php#ini.open-basedir

  2. Another possibility is that your file access right (for uploaded files) are not set in a way, that your script is allowed to access them. With some security settings enabled (on a linux server), your PHP script can only access files owned by the same user as the "owner" set for the script file. After upload via "ftp" this is most probably the usersname of the ftp user. If edited on the shell, this will be the current users username. => But: Uploaded files are sometimes assigned to the user the webserver is running as (e.g. "www-data", "www-run" or "apache"). So find out which it is and assign your script to this owner.

  3. For file uploads you should use move_uploaded_file(...) which is explained here: www.php.net/manual/en/function.move-uploaded-file.php ; If you don't do this, the file access right may be wrong or you might not be able to access the file.
SDwarfs
  • 3,074
  • 5
  • 23
  • 52