0

I have a login page that when a user logs in, it starts a session using the id for that user which has been fetched from a mySQL database.

$_SESSION['logged_in'] = $db_id;

On the user's profile page there is the option to update their personal info. The href for this page uses a GET parameter of the username which is passed into the url

A database fetch is then done on the profile-edit page to make sure that the GET url parameter username returns the user id of the person with that username.

isset($_GET['username']) ? $username = $_GET['username'] : header("Location: index.php");

$stmt = $connection->prepare("SELECT * FROM users WHERE username=:username"); 
$stmt->execute([
    ':username' => $username
]); 

if ($stmt->rowCount() !== 0 ) {

    $row = $stmt->fetch();

} else {
    header("Location: index.php");
}

$db_id = htmlspecialchars($row['id']);

A check is then made to ensure that the $_SESSION value matches the $db_id value. This is done to prevent someone typing in a different username into the url so they can change that person's details.

// EXIT IF NOT LOGGED IN USER
if ($db_id != $_SESSION['logged_in'] ) { header("Location: index.php"); exit; }

The final part of the above code works, but when I do !== for 'identical to' instead of != for equal to, the code fails?

I've checked both values using gettype() with the following:

echo gettype($_SESSION['logged_in']);
echo gettype($db_id);

Both are returned as 'integer'.

Why does the check fail with !== but not with != when they are the same numeric value, and both values are showing as the integer data type?

pjk_ok
  • 618
  • 7
  • 35
  • 90
  • Does this answer your question? [Not equal to != and !== in PHP](https://stackoverflow.com/questions/3641819/not-equal-to-and-in-php) – Kinglish Jun 05 '21 at 00:32

1 Answers1

1

htmlspecialchars() returns a string. When you compare $db_id != $_SESSION['logged_in'], $db_id is being automatically converted to an int to be compared with $_SESSION['logged_in'], which is why the !== comparison is failing.

gettype() returns the type of the value of the $variable, not the type of the variable itself. use is_int() and is_string() to test for the type of the variable.

wetmarble
  • 185
  • 1
  • 6
  • 1
    Not sue what this means _gettype() returns the type of the value of the $variable, not the type of the variable itself_ https://3v4l.org/4mLAs – AbraCadaver Jun 05 '21 at 01:19
  • I think I was distracted by my kids when I wrote that. Looking back at it now, I admit, it doesn't make sense. – wetmarble Jun 05 '21 at 04:42