保护PHP页面的最佳方法是什么?

I want to implement a login system on my website that redirects a user to login.php if they are not currently logged in. I am currently using this approach :

<?php 
start_session();

if (!isset(_SESSION['user_id']))
{
    header('location:login.php');
    exit();
}
$user_details = get_user_details_from_db(_SESSION['user_id']');
?>

<html lang="en">
<head>  <meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<p><?php echo "Welcome $user_details['name']?> You are in a protected area</p>
</body>
</html>

or should I encapsulate the entire contents in an if then else, such as :

<?php 
start_session();

if (isset(_SESSION['user_id']))
{
    $user_details = get_user_details_from_db(_SESSION['user_id']'); 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>  <meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<p><?php echo "Welcome $user_details['name']?> You are in a protected area</p>
</body>
</html>
<?
}
else
{
    header('location:login.php');
    exit();
}
?>

I've seen both methods being used in places, so wondering if there is any issue with the first method.

Thanks.

You can combine both methods. 1st for protecting whole pages and the 2nd one for for example protected buttons or links which are directed to protected pages.

Well, you can do both methods. The only error you'll get in the first one, is you forgot a $ on line 9. If you really want to secure your site, you should check if you get user details for your ID you get from your session.

I prefere the first method. If the session is not correct then redirect and end execution, else continue. Additionaly you can check if user details is correct:

$user_details = get_user_details_from_db($_SESSION['user_id']);
if (!isset($user_details['name']) {
    // redirect..
    exit();
}