0

I have a login script that I am using that is currently working, but I want to add some additional functionality such as displaying name, some prefs etc. I'd like to store the users ID in the session so I can use it as they navigate the site for lookups, but I'm not sure how to go about this. Any help is greatly appreciated... code is below.

<?php
include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/magicquotes.inc.php';

if (isset($_GET['login'])){
include 'login.html.php';
exit();
}

if (isset($_GET['security'])){
ob_start();
$host="localhost"; // Host name 
$username="*****"; // Mysql username 
$password="*****"; // Mysql password 
$db_name="*****"; // Database name 
$tbl_name="users"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Define $myusername and $mypassword 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect home"
session_register("myusername");
session_register("mypassword"); 
header("location:/admin/");
}

else {
echo "Wrong Username or Password";
}
ob_end_flush();
exit();
}

if (isset($_GET['logout'])){
session_start();
session_destroy();
header("location:/admin/");
exit();
}   
session_start();
if(!session_is_registered(myusername)){
header("location:?login");
}

// Display Home Page

include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';

include 'home.html.php';
exit();
4

1 回答 1

1
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect home"
session_register("myusername");
session_register("mypassword"); 
header("location:/admin/");
}

在这里,在 if 语句中,您应该再次查询数据库并选择要在会话中使用的名称等。

在 if 语句中启动会话

// Register $myusername, $mypassword and redirect home"
$query = "SELECT `first_name` FROM `table` WHERE `username`=$username";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$firstName = $row['first_name'];

session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['firstName'] = $firstName;
header("location:/admin/");

显然我不知道你的数据库结构是什么样的,但我希望你明白

然后您在用户应该登录的页面上启动一个会话,然后您可以通过以下方式访问名字

例如

echo $_SESSION['firstName'];
于 2013-04-30T21:19:58.847 回答