Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8383703
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T17:13:32+00:00 2026-06-09T17:13:32+00:00

End goal: Click link on page 1, end up with file downloaded and refresh

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T17:13:33+00:00Added an answer on June 9, 2026 at 5:13 pm

    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: http://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.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

can I load a ps1 file from within a ps1 file. The end goal
The end goal is to have some form of a data structure that stores
My end goal is to create a firefox extension that inserts an HTML button
Note: I've only been using Objective-C for a week. Here's my end goal: I
My end goal is to be able to send: $('[data-track]').live('click', function () { mpmetrics.track(Share,
I'm using acts_as_taggable_on, but now have a new requirement: The end goal: Users should
The end goal of this part of my project is to be able to
My end goal is local development of a Radiant CMS installation. So, need rails
This is for the Apple platform. My end goal is to do a find
First off, let me define the end goal: I'd like to Wordpress (version 2.8)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.