php页面受角色保护但不受客人攻击

I am trying to protect some php pages with roles. The code i am using its working when the people make the login but if they know the link and don't make the login they can access the page and i can't understand why.

Can anyone help me?

I am using this code to protect the page where only users with role "admin" can access.

<?php
// Initialize the session
session_start();

// If session variable is not set it will redirect to login page
if(isset($_SESSION['username'])){if ($_SESSION['role']=='admin') {

} else {
  header('location: index.php');
}
}
?>

Try this:

<?php
    // Initialize the session
    if(!isset($_SESSION)) {
        session_start();
    }

    // If session variable is not set it will redirect to login page
    if(empty($_SESSION['username'])) {
            header('Location: index.php');
    } else {
        if ($_SESSION['role'] != 'admin') {
            header('Location: index.php');
        }
    }
?>