Search code examples
phpsessiondestroy

PHP Sessions... (Must destroy)


I want to create a PHP session for my website...

I want that, once anybody starts a session, it could only see/visit specific pages of the website... And when he/she clicks some other link (i don't want him to visit), the session must destroy...

And he must have to enter username/password the next time he/she want to start a session...

    $con=mysql_connect("localhost","root","");
    mysql_select_db("school", $con);

    $un=$_POST["username"];
    $pass=$_POST["password"];

    $query= "SELECT username FROM login where username= '".$un."' AND  password = '".$pass."' ";
    $result = mysql_query($query)or die(mysql_error());
    $data = mysql_fetch_array($result);
    $rows = mysql_num_rows($result);
    if($rows > 0)
    {
        session_start();
        $_SESSION['username']=$data['username'];
        header("location: ../Index3.html");
    }
    else
    {
        header("location: ../Pages/Admin_panel.html");
        ?>
        <script>
        alert("Unable to Sign In!");
        </script>
        <?php
    }

Thanks in advance!


Solution

  • So first of all, there :

      header("location: ../Pages/Admin_panel.html");
      ?>
      <script>
      alert("Unable to Sign In!");
      </script>
      <?php
    

    Everything following the header() relocation won't get executed.

    Instead you can use :

    else
    {
        ?>
        <script>
        alert("Unable to Sign In!");
        window.location.replace('/Pages/Admin_panel.html')
        </script>
        <?php die();
    }
    

    Then in your other pages which require rights, add the following code :

    <?php
    
    if($_SESSION['user_rights'] != 'admin'){ //whatever rights he would need to access this page
        session_destroy();
        header("location: ../Pages/login.html"); //your login page.
    }
    ?>