显示登录用户的用户名,并为其他用户显示注册/登录链接


Show username for logged users and sign up/login links for others

我真的需要帮助我的登录脚本。我想显示一些PHP代码显示登录用户的用户名,其他用户只显示登录/注册链接。

代码如下。

/*---Logged in user's homepage---*/

<?PHP
require_once('../lib/connections/db.php');
include('../lib/functions/functions.php');
checkLogin('2');
$getuser = getUserRecords($_SESSION['user_id']);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><?=$getuser[0]['username'];?>'s Profile Page | HDS Web</title>
<?php include('../headother.php'); ?>
<div style="background:#FFFFFF; padding-bottom:150px; padding-top:15px;">

/*----User's photo and details section goes below----*/

<div style="float:left; width:600px;">  
<p>
Welcome <?php if(empty($getuser[0]['first_name']) || empty($getuser[0]['last_name'])){echo $getuser[0]['username'];} else {echo $getuser[0]['first_name']." ".$getuser[0]['last_name'];} ?></p>                       
 <? displayUserImg($getuser[0]['id']); ?>
</div>

/*---User's navigation menu section goes below---*/

<div style="float:right; width:200px;"> 
    <a href="index.php">Home</a> | <? if (!empty($getuser[0]['thumb_path'])){echo "<a href='manage_photo.php'>Manage My Photo</a> | ";} else {echo "<a href='upload_photo.php'>Upload Photo</a> | ";} ?>
<a href="change_pass.php">change password</a> | 
<a href="edit_profile.php">Edit Profile</a> 
| <a href="log_off.php?action=logoff">sign out</a></div></td>

    </div>
    <?php include('../footer.php');?>

</body>
</html>

你可以这样做:

if(isset($_SESSION['user_id'])) {
  // detected a valid user
  ?>
  <p>Welcome <?php if(empty($getuser[0]['first_name']) || empty($getuser[0]['last_name'])){echo $getuser[0]['username'];} else {echo $getuser[0]['first_name']." ".$getuser[0]['last_name'];} ?></p>
  <?php                  
  displayUserImg($getuser[0]['id']);
} else {
  // didn't login, show login link
  echo '<p><a href="login.php">Login Link</a></p>';
}

在注释中提到,检查$_SESSION['user_id']并不能保证准确的结果,因为当数据库中没有找到user_id时,函数可能不会返回用户对象。最好从getUserRecords()的返回值来判断。

指出:

  • 你的DOCTYPE在哪里?
  • 你的HTML可能无效,没有关闭<head>和打开<body>标签(好吧,它可能包含在你的包含文件。谁知道呢?)
  • 停止使用内联CSS
  • 建议不要使用<?。使用<?php代替