SMH SMH - 2 months ago 5
PHP Question

Open CSV file in browser instead of being downloaded HTML

Just wondering if there is a way to open the csv file in the browser instead of being downloaded?

My code:

<a href="Myfile.csv">Open</a>

Answer

With a Code like this: <a href="Myfile.csv">Open</a>, You are really not doing any download. However, if the Client Browser doesn't have the capability to read/render the File (in this case .csv File), it will force the user to download the file instead. To explicitly enforce a Download, you have to set the header so as to tell the Browser how to handle the Request for the File in Question. Consider this over-simplified Script:

PHP SCRIPT: CONTAINING HTML MARKUP

<?php   // NOTICE THAT THERE IS NO WHITE-SPACE OR OUTPUT BEFORE <?php
        // AND ALSO; NO "echo" STATEMENT AT ALL BEFORE THE if(isset()){} BLOCK.

        if(isset($_GET['d'])){
            $file = htmlspecialchars(trim($_GET['d']));
            processDownload($file);
        }

        function processDownload($fileName) {
            if($fileName){
                $dldFile    = $fileName;
                if(file_exists($fileName)){
                    $size       = @filesize($fileName);
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename=' . $fileName);
                    header('Content-Transfer-Encoding: binary');
                    header('Connection: Keep-Alive');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . $size);
                    return TRUE;
                }
            }
            return FALSE;
        }

    ?>


    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Download Example</title>
        </head>
        <body>
            <div class="container">
                <div class="col-md-12">
                    <!-- Myfile.csv IS IN THE SAME DIRECTORY AS THIS FILE: index.php -->
                    <!-- OTHERWISE; SET THE PATH TO THE CSV FILE AS VALUE OF d -->
                    <!-- NOTICE THAT THE LINK TO DOWNLOAD HERE IS THE SAME URL -->
                    <!-- WITH A QUERY PARAMETER ?d=Myfile.csv APPENDED TO IT.-->
                    <a href="index.php?d=Myfile.csv">Download CSV</a>
                </div>
            </div>
        </body>
    </html>

It is hoped, this might give you a Clue on how to go about it your own way.

Good-Luck and Cheers ;-)

Comments