mysql和php - 基于用户登录从数据库检索数据 [英] mysql and php - Retrieving data from database based on user logged in

查看:165
本文介绍了mysql和php - 基于用户登录从数据库检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我开始尝试创建网站之前,我想知道是否从数据库中提取用户内容取决于哪个用户登录可以由一个$ _SESSION变量确定。例如,如果我想要用户'example'的所有消息:

  $ _ SESSION ['username'] = $ _POST [ 'username'] //用户登录时设置
$ username = $ _SESSION ['username']

$ data = mysql_query(select * from messagesTable where username ='$ username '')
while($ row = mysql_fetch_array($ data)){
echo $ row ['message']
}

我想知道这是否是正确的方法来做这样的事情,如果它安全地返回基于会话变量的(个人)数据。 p>

我没有这些语言的经验,但我喜欢学习经验,请告诉我如果不清楚。感谢。

解决方案

可以安全地根据 $ _ SESSION variable如果你确定它的有效性,因为你自己在代码中设置。根据您从 $ _ POST 获得的会话变量返回数据是不安全的



您最初设置

  $ _ SESSION ['username'] = $ _POST ['username']; 

因此,除非您使用密码或其他方式验证此用户是他声称的用户不应使用 $ _ POST ['username'] 返回其他信息。如果您的登录过程(我们在上面看不到)已经验证 $ _ POST ['username'] 有效,您可以使用它作为源来检索其他信息。 / p>

您还需要过滤SQL注入:

  $ _ SESSION ['username'] = mysql_real_escape_string($ _ POST ['username']); 


before I go ahead and attempt to create a website, I wanted to know if pulling a users content from a database depending on which user is logged in can be determined by a $_SESSION variable. So for example if I want all the messages for user 'example':

$_SESSION['username'] = $_POST['username'] // set when the user logs in
$username = $_SESSION['username']

$data = mysql_query("Select * from messagesTable where username = '$username'")
while($row = mysql_fetch_array($data)) {
echo $row['message']
}

I wanted to know if this would be the right way to do something like this and also if its safe to return (personal) data based on a session variable.

I haven't got that much experience in either of these languages but I like to learn with experience, please tell me if it's not clear. Thanks.

解决方案

It is safe to return user data based on a $_SESSION variable if you are certain of its validity because you set it yourself in code. It is not safe to return data based on a session variable that you get from $_POST.

You initially set

$_SESSION['username'] = $_POST['username'];

So unless you have verified with a password or otherwise that this user is who he claims to be, you should not use $_POST['username'] to return other information. If your login process (which we cannot see above) already verifies that $_POST['username'] is valid, you can use it as a source to retrieve additional information.

You will need also to filter against SQL injection:

$_SESSION['username'] = mysql_real_escape_string($_POST['username']);

这篇关于mysql和php - 基于用户登录从数据库检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆