简体   繁体   中英

Is PHP SESSION safe in website for inserting MySql data

I have a website where I create session of a UserID if login Successful .

$email = mysql_real_escape_string($_POST["email"]);
if(LOGIN SUCCESSFUL) {
$_SESSION['userID'] = $email;
}

Then in whole site where ever I enter any data into MySql, I insert user_id from $_SESSION['userID']

I don't know how secure it is, if not please suggest me any secure way to do all this.

There's nothing fundamentally wrong with it - anything you store in $_SESSION is, as Barmar already said, reasonable secure. However, using the user's E-Mail as the primary ID internally, and storing the user ID directly in $_SESSION , is not a great idea architecturally.

The more common approach is to be a bit more abstract: store only a session ID in $_SESSION .

That ID often points to a "sessions" database table. There is a record for each session in that table, and its status - when it was created, when it's going to time out, whether the user is logged in, etc.

You can theoretically store all this directly in $_SESSION but then you have no central place where you can see who is currently logged in, which is important for troubleshooting, and log out everyone at once.

That "sessions" table will contain a user ID, which points to a separate "users" table. That ID is ideally a numeric auto-increment value, and the E-Mail is just a column in the users table. That allows relations to other tables to stay intact even when the E-Mail changes. Using the ID, you can get the E-Mail address from that table.

It's more complicated but it saves you a lot of trouble in edge cases, eg when a user changes their E-Mail address.

Session data is reasonably secure. It's held on the server, not the client. The only thing the client has is a session ID string, which is a random string that the server uses to find the session data in its files.

When inserting anything in a database, make sure it's safe. You're already using mysql_real_escape_string() , which is a good start, since it will prevent most common SQL injection problems (not all though!).

Since you're expecting an email address, it might also be wise to use filter_var() , since it allows you to check if it is in fact a valid address.

if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
    // Email is valid, do something with it.
}

Once you've made sure it's safe, you can use it in the database where ever you like. You no longer need to escape it for every query, since you've already ensured it is safe. If you really want to be safe, use the users ID (not their email), since numeric values are almost impossible to put junk in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM