How to unset global variable in php?

Bernard picture Bernard · Sep 12, 2014 · Viewed 19.6k times · Source

I know very basic of php and web programming. Here is my php code. I have seen couple of similar questions. They unset global variable with unset function. I want every time user open the url, a username and password prompt and after entering username password if it is correct download the file and delete username and password and if is wrong delete username and password and again prompt for username password.

<?php    
    function destroy_foo()
    {
        if (isset($_SERVER['PHP_AUTH_USER'])) {
            unset($_SERVER['PHP_AUTH_USER']);       
        }
        if (isset($_SERVER['PHP_AUTH_PW'])) {
            unset($_SERVER['PHP_AUTH_PW']);
        }
    }

    if (!isset($_SERVER['PHP_AUTH_USER'])) {

        header('WWW-Authenticate: Basic realm="My Realm"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Text to send if user hits Cancel button';
        exit;
    } else {

        echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
        echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";

        $file = 'welcome.txt';
        if($_SERVER['PHP_AUTH_PW'] == "admin" && $_SERVER['PHP_AUTH_USER'] =="admin"){
            destroy_foo();

            if (file_exists($file)) {

               //Do some task
                destroy_foo();
                exit;
            }
        }
        else
        {
            //Do some task
            destroy_foo();

        }
    }
    ?>

At the moment username and password stays in the global variables for some reason. I'd appreciate if you could give suggestion or hint.

EDIT

This did not work either:

function destroy_foo()
{

    if (isset($_SERVER['PHP_AUTH_USER'])) {

        unset($_SERVER['PHP_AUTH_USER']);
        $_SERVER['PHP_AUTH_USER'] = null;

    }

   if (isset($_SERVER['PHP_AUTH_PW'])) {

       unset($_SERVER['PHP_AUTH_PW']);
       $_SERVER['PHP_AUTH_PW'] = null;

   }
}

Link to file: http://behzadgarekani.net16.net/

Answer

Rodrigo Techera picture Rodrigo Techera · Sep 12, 2014

I think you are doing it good with unset() function but I am seeing a little unordered code. I think that in this way you will can do that you wanted:

function destroy_foo() {
    if(isset($_SERVER['PHP_AUTH_USER']))
        unset($_SERVER['PHP_AUTH_USER']);       

    if (isset($_SERVER['PHP_AUTH_PW']))
        unset($_SERVER['PHP_AUTH_PW']);
}

if(isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']=='admin' && isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW']=='admin') {
    //download the file

    destroy_foo();
} else {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
}