Jump to content

Authenticate user before downloading file


tamanna

Recommended Posts

Hello,

 

I want the user to get authenticated before file download starts

 

Here is my code:

 

 <?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Your request is cancelled';
    exit;
} else {
    //check $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']
    if (isset ($valid)) {
        //start download

        $path = './data/negative_seq_60.txt';
        $type = "text/plain";

        header("Expires: 0");
        header("Pragma: no-cache");
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: pre-check=0, post-check=0, max-age=0');
        header("Content-Description: File Transfer");
        header("Content-Type: " . $type);
        header("Content-Length: " .(string)(filesize($path)) );
        header('Content-Disposition: attachment; filename="'.basename($path).'"');
        header("Content-Transfer-Encoding: binary\n");

        readfile($path); // outputs the content of the file

        exit();
    } else {
        //show error
    }
}
?>

 

But on clicking download link, I am getting the following error : " Undefined variable: valid at line no 9".

 

Please help.

Well that would make sense for the error, where are you getting a value of $valid from.  The code you provided doesn't have a $valid defined anywhere before trying to compare it's value in the if().  Maybe it's supposed to be something like $_SESSION['valid'], but it's all dependent on how you defined $valid in the first place and where.

 

Scratch that, I didn't see you were checking isset($valid) which shouldn't cause an error like that. Try removing the space between the isset and the ($valid), it's most likely not reading the isset properly.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.