phpwordpresswordpress-plugin-creation

how can I catch a redirect and downloading a generated file instead?


I am creating a plugin which generates a CSV file and allows an admin to download it. I have a working function which generates the CSV data, but I'm having trouble making it downloadable. I have tried the solution from this question but it doesn't seem to be catching the redirect. Here is the element that causes the redirect:

<form method="GET" action="data.csv">
    <input type="submit" class="button button-primary" value="Download CSV"></input>
</form>

This is what I have so far for catching the redirect:

function download_redirect() {
   if ($_SERVER['REQUEST_URI']=='/wp-admin/data.csv?') {
       $csv_data = generate_csv();

       header('Content-Disposition: attachment; filename="data.csv"');
       header('Content-Type: text/csv');
       header('Content-Length: ' . strlen($csv_data));
       header('Connection: close');

       echo $csv_data;
    
       exit();
   }
}
add_action('template_redirect','download_redirect');

the function generate_csv() returns the contents of the CSV file as a string. What am I missing?


Solution

  • Thank you to @CBroe for giving me the idea that finally helped me solve this. I was approaching this in the wrong way. Instead of trying to intercept requests, I was able to use a different hook, updated_option, which runs after options update, and return the CSV file then. Here is what worked:

    <form method="GET" action="data.csv">
       <input type="submit" class="button button-primary" value="Download CSV"> 
       </input>
    </form>
    

    And the hook ("eud" is the prefix I am using for all settings):

    function download_redirect( $option_name ) {
        if (substr($option_name, 0, 3) == "eud"){  //$_SERVER['REQUEST_URI']=='/wp-admin/data.csv?') {
           $csv_data = generate_csv();
    
           header('Content-Disposition: attachment; filename="data.csv"');
           header('Content-Type: text/csv');
           header('Content-Length: ' . strlen($csv_data));
           header('Connection: close');
    
           echo $csv_data;
        
           exit();
        }
    }
    add_action('updated_option','download_redirect');