logout in php

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phpuser123
    New Member
    • Dec 2009
    • 108

    logout in php

    Hi,I have created a script where I want to use onclick event and javascript to log out.Here r my coodes ..
    Code:
    <script type="text/javascript">
                        function logout(){
    				<?php session_destroy();?>
    			}
    </script>
    
    <body>
    <a href="#" onclick="logout()">logout</a>
    </body>
    Whenever,I reload the page,the sessions variables are destroyed without pressing the logout link...
    I want know how this is achieved and how can I logout from a session..

    Any help will be kindly appreciated.Tha nk s
    Last edited by Dormilich; Jan 10 '10, 02:22 PM. Reason: Please use [code] tags when posting code
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    that is because the PHP (that is, the session_destroy () function) is executed before the complete HTML is sent to the browser and JavaScript can be executed. (also note the output of your PHP code in the HTML source code – there shouldn’t be any)

    to solve this there are several possibilities
    1) make an AJAX call to a PHP script file, that executes session_destroy ()
    Code:
    // JavaScript, pseudo code
    function logout()
    {
        // simply calling the logout.php page
        Ajax.post("logout.php");
    }
    // PHP
    <?php # file: logout.php
        session_start();
        session_destroy();
    ?>
    2) submit a form (you only need the submit button) to this page and if the button was pressed, destroy the session.
    Code:
    // HTML/PHP
    <form action="" method="post">
        <input type="submit" name="logout" value="yes">
        <?php
            if (isset($_POST["logout"]))
            {
                session_destroy();
            }
        ?>
    </form>
    3) reload the page via JavaScript, passing an URL parameter indicating the session to be killed.
    Code:
    // JavaScript
    function logout()
    {
        window.location.href = "page.php?logout=yes";
        <?php
            if (isset($_GET["logout"]))
            {
                session_destroy();
            }
        ?>
    }

    Comment

    Working...