1

I'm trying to save the output of a function into a variable.The function RandomStr() only runs one time and generates a string ; I'm trying to grab that result the first time and store it into a variable. I tried several ways of session storage but none of them seem to work . The value is stored the first time into $userId but when I go to a different page or if I reload the current page , It's gone .After that I'll be storing that userId into MySQL . Any suggestions ?

Thank you

        //
        function RandomStr($length = 10)
        {
            session_start();
            $state = $_SESSION['state'] ?? false;
            if ($state) return;

            $_SESSION['state'] = true;

            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $charactersLength = strlen($characters);
            $randomString = '';
            for ($i = 0; $i < $length; $i++) {
                $randomString .= $characters[rand(0, $charactersLength - 1)];
            }

            return $randomString;
        }

       $userId = RandomStr();
       echo $userId;

        //
Thatdude22
  • 57
  • 9
  • save the returned value in your session but add a check if your session has this value before don't update it, or if you use `oop` search for a concept called `singleton` – Joseph Jan 21 '20 at 18:18
  • 2
    `$_SESSION['userid'] = $userId;` should do it. Make sure all the pages that need it begin with `session_start();` – Barmar Jan 21 '20 at 18:19
  • singleton won’t persist after script ends... so won’t be there for the next page. – Tim Morton Jan 21 '20 at 18:21
  • Storing token in session will work only for logged in users, I would store in database to use when ever I need. –  Jan 21 '20 at 18:22
  • @Dilek I'm not making a login system yet. This is for guests – Thatdude22 Jan 21 '20 at 18:29
  • @Thatdude22 I think you have 2 ways to save token, 1. Add a column named token into your table (The one you want to save token in) and insert token in that column which is much easier than solution two. 2. you can write that token in a text file using `fopen()` and use in next time Fopen : https://www.php.net/manual/en/function.fopen.php –  Jan 21 '20 at 18:39
  • @Dilek I tried the first way before. Take a look . https://imgur.com/C3FhmV1 and then this is the db https://imgur.com/10RjR9f . It only adds token once. – Thatdude22 Jan 21 '20 at 18:46

1 Answers1

1

To store a value in a session, you need to actually store that value in a session:

<?php 
// good practice is just to start off with session_start() if you need a session.
session_start();

/**
 * Get user id from session or create new one and store in session
 *
 * @return $userId
 **/
function getUserId($length = 10)
{
    if(!empty($_SESSION['user_id'])) {
        return $_SESSION['user_id'];
    }

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

    $_SESSION['user_id'] = $randomString;
    return $randomString;
}

$userId = getUserId();
echo $userId;

Why sessions?

Web pages are stateless, i.e., no value in a script will be saved from one execution of a page to another, nor will any other page know what a value is unless it is passed to it or stored in some persistent storage that both pages have access to. As mentioned in the comments, not even a singleton will hold state between executions of a script; it is only good for the duration of the script execution.

How do sessions work?

Per the documentation,

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions...

The data is not saved in a cookie; by default it is saved on disk by PHP. The cookie just tells PHP which data to use.

So, if you want to save $userId, you save it in a session; usually using the same name for clarity. So in this example, $_SESSION['userId'] = $userId; But you could just as easily do $_SESSION['billyBob'] = $userId;, you just have to remember what you named it in the session array.

You do not have to be "logged in" for sessions to work. In fact, just the opposite is true: you cannot be "logged in" (and remain that way) without sessions working first (unless you create your own method of tracking who is executing a script).

How long do sessions last?

By default, only 30 minutes according to How long php sessions are stored in server? For this reason, don't consider session storage to be permanent. It is only intended to keep state for a short period of time. If you need anything longer, you will need to use a database or file. To identify your user, you will need to set a cookie with an identifying token, or let the user remember the userId and submit it to your script. But if that cookie is cleared and you have no login-- that user will lose everything.

Community
  • 1
  • 1
Tim Morton
  • 2,614
  • 1
  • 15
  • 23