sg552
sg552

Reputation: 1543

Is it safe to insert data to database using id from session?

From here: PHP $_SESSION is server side or local? I understand that session is server side only and client can't tinker with it.

So I assume it is a safe approach to set id from database to client session id and use it as identification to insert into database?

For example I'm doing like this right now for identification on all my page: login.php

    $result = mysqli_query($con, "SELECT id, name, password FROM user_data WHERE email_address = '$email' AND status = '1'") or die(mysqli_error($con));

        $row = mysqli_fetch_assoc($result);

            if (password_verify($password, $row["password"])) {

                $userinfo = array();
                $userinfo['id'] = $row["id"];
                $userinfo['name'] = $row["name"];
                $_SESSION['userinfo'] = $userinfo;
                header ("Location: insert.php");    

            }

and on insert.php page

$result = mysqli_query($con,"INSERT INTO client_data (`data`, `id`) VALUES ('$value', ".$_SESSION['userinfo']['id'].")");

Upvotes: 1

Views: 181

Answers (1)

janos
janos

Reputation: 124714

$_SESSION['userinfo']['id'] is only as safe as you make it. Trusting whatever is in it means trusting all the publicly accessible PHP scripts to work correctly, with no possibility to abuse them to set $_SESSION['userinfo']['id'] to something nasty.

That's really a lot of trust. I don't think that's affordable. Especially when this can be done more securely using prepared statements quite easily.

if ($stmt = $mysqli->prepare("INSERT INTO client_data (`data`, `id`) VALUES (?, ?)")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $value);
    $stmt->bind_param("s", $_SESSION['userinfo']['id']);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($result);

    /* fetch value */
    $stmt->fetch();

    /* close statement */
    $stmt->close();
}

Using prepared statements will also have the additional benefit of the RDBMS optimizing the queries, making repeated queries faster.

Upvotes: 1

Related Questions