Retrieve User ID in PHP

Steve Sohcot
1 min readNov 30, 2020

--

A quick tip I’ll be using on my future web applications: store the User ID as a constant.

When you have users who log in to your site, you’ll most likely give each one a unique “User ID” — probably in a Session variable. One of the first things I do with my code is to set this session variable value in a PHP constant. It’s not sufficient to store it in a “local” variable for many of my purposes.

I use a lot of PHP functions, and I’d rather not have to pass this in as a parameter. Due to variable scope limitations, you can’t reference a local variable, but you can reference a constant within a function.

Just do this:

define("USER_ID", intval($UserID) );

Obviously you need to set $UserID equal to the right value, for example with this:

$UserID = intval($_SESSION['USER_ID']);

You may have some other logic if that’s NOT set, to to check a user’s cookies to get the value…

But once you have the value, define it as a constant so you can use constant(‘USER_ID’) anywhere.

--

--

No responses yet