session_status() : used to detect the status of the current session. It returns one of the following three constants:
PHP_SESSION_DISABLED : The session function has been disabled.
PHP_SESSION_NONE : The session has not started.
PHP_SESSION_ACTIVE : The session has started.
session_id() : Used to get or set the ID of the current session. This ID is the unique identification mark for the session between the client and the server, and is usually present in the form of a cookie.
In some complex applications, multiple calls to session_start() may result in a "headers already sent" error. In order to avoid repeated start of sessions, it is recommended to use session_status() to determine the current status:
<code> if (session_status() === PHP_SESSION_NONE) { session_start(); } </code>This method ensures that the session is started before it is opened, preventing unnecessary errors.
After starting the session, you can get the unique identity of the current session through session_id() . This logo is useful when debugging, logging, or manually tracking user behavior.
<code> echo 'The current session ID is: ' . session_id(); </code>User behavior tracking can be achieved by recording session_id() to the log or database, for example:
<code> file_put_contents('/var/log/php_session.log', session_id() . " - " . date('Ymd H:i:s') . "\n", FILE_APPEND); </code>In some scenarios, we may want to manually specify the session ID, for example for cross-system session sharing. At this point, you can use session_id() to set it before calling session_start() :
<code> if (isset($_GET['sid'])) { session_id($_GET['sid']); } session_start(); </code>For example, you can use the following link to carry the session ID:
<code> <a href="https://gitbox.net/app.php?sid=customsession123">Click to enter</a> </code>Note: Manually setting the session ID may pose security risks (such as session hijacking). When using it, you should ensure that the parameters are sourced reliably, or use them in combination with the token mechanism and HTTPS.
Before processing a user request, you can check whether the session has been created. If not, the user can be prompted to log in or re-initialize the status.
<code> if (session_status() !== PHP_SESSION_ACTIVE || session_id() === '') { echo 'The session has not been initialized or has expired. '; } else { echo 'Current session ID: ' . session_id(); } </code>This approach is particularly important in large systems, especially when it is necessary to ensure that the user identity has been identified by the session before certain operations.