H2S53: How to use $_SESSION and $_COOKIE to register # a persistent user logged-in:


Krossing<1:24, D>: “ID inside of our session”

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
https://www.w3schools.com/php/php_sessions.asp

A session is started with the session_start() function.

Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).

Hu: ^connect to my ghost variable idea. How does it work? How does it know it’s me?

W3: Most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.

Quote: Destroy a PHP Session: To remove all global session variables and destroy the session, use session_unset() and session_destroy():

^Hu: Logout button

Quote: A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

^A cookie is created with the setcookie() function.

W3: setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.

W3: PHP Create/Retrieve a Cookie
The following example creates a cookie named “user” with the value “John Doe”. The cookie will expire after 30 days (86400 * 30). The “/” means that the cookie is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie “user” (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

+code example https://www.w3schools.com/php/php_cookies.asp

W3: Note: The setcookie() function must appear BEFORE the tag.

W3: Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie() function:

Hu: Use the present cookie to establish the present session, at session start, then use the session to carry the main variables; why do we need session, when it seems like cookie does the same thing, but can also persist across sessions?

Krossing.2-hours:

  • file name notation, uses -in for files that are includes, but not displayed
  • thematically, an includes folder, what I call a lib, look for it in each WP-core and plug-in install, for inspo-functions
  • Hu: place site.wide-usable functions in a single functions-inc.php file
  • every registration error header directs # to a different url.error-page

Krossing: sessions & cookies:

  • $_cookie is stored on users computer, less sensitive info; set an absolute time limit; time() is current time
  • $_session is stored on server; can map a username session variable to the username, user entered, in the input field

Hu: WordPress already tracks # $_cookie and $_session.

Kinsta.com<a-r>: Cookies were first invented in 1994 by a computer programmer named Lou Montulli. When you try to access the back-end of your WordPress site, a check is done to see if the two cookies above exist and haven’t expired. This is what allows you to magically bypass the wp-login.php screen. 😉WordPress also sets wp-settings-{time}-[UID] cookies. The ID being your user ID from the WordPress users database table. This stores personal dashboard and admin interface settings. If you have a popup box on your WordPress site and a visitor closes it, this typically will set a cookie so that it doesn’t come back again. Items added to a shopping cart on your ecommerce site. A cookie is stored so that the shopping cart keeps your products while you continue to browse around the site. When it comes to WordPress cache, this is where things get tricky. Caching is essentially the process of storing resources from one request and reusing those resources for subsequent requests. Basically, it reduces the amount of work required to generate a page view.

^ PHP Sessions

Quote: PHP sessions is an alternative to the standard cookie approach. It’s still a cookie, but it’s called PHPSESSID and is typically stored in the /tmp/ directory on the web server itself. The way the server knows to associate a given session with a given request is that it’s also stored in an HTTP cookie.

Phase-1 implementation:

Hu: phase.1-implementation involves only session functions and the $_SESSION super #. We will capture a username using a login form # and assign this username to $_SESSION[‘username’]; in a separate redir: /process-redir/login.validate-redir,test.php. When this variable is empty, because users are looking at the site without loggin in #, we will assign a dummy username, ‘visitor’:

session_start();

Hu: This single | line is provided as a php.built-in, who is very | prescriptive about its use. We have to insert this, at the top of every | page on our site, that users will visit, during a continuous | session. If there are any pages that do not contain this #, the session will be broken.

<form action="/process-redir/login.validate-redir,test.php" method="post">
  <label for="username">Username</label><br>
  <input type="text" id="username" name="username" value="Enter-username" minlength="1" maxlength="18"><br>
  <input type="submit" name="submit" value="Login"><br><br>

Hu: This simple | HTML-form captures a username and posts it # to a processor, /process-redir/login.validate-redir,test.php. We will add this to a page login.php.

<p><a href="session.var-assign.php">Refresh</a></p>

Hu: A simple refresh button # that we will use, at times, to test session continuity #

function empty_sess_uname_check() {
	if (empty($_SESSION['username'])) {
		$_SESSION['username'] = 'visitor';
		// This $_SESSION['username'] does not need to be returned. 
	}
}

Hu: Added to login.functions-inc.php, this function will assign the string ‘visitor’ to $_SESSION[‘username’] whenever a user visits a page with session_start(); and does not have an assigned username, ie that they are loggedout. Establishing a username, even for logged.out-users, is important, for our securityfeatures.

include 'C:\wamp64\www\personal-dash\php_local_libs\login.functions-inc.php';
empty_sess_uname_check();

Hu: This include is already present in most of our docs, but we will add the function call to empty_sess_uname_check() as well, and note that this needs to be placed in scripts above any usage of $_SESSION[‘username’]

session_destroy();

Hu: Another single | line provided directly by # PHP: this was used, as a comment-conditional, to destroy sessions, if necessary, during testing.

echo $_SESSION['username'];

Hu: The handy-dandy echo statement was also used, regularly, to check the current value assigned to the $_SESSION[‘username’] variable.

session_start();
$_SESSION['username'] = $_POST['username'];
header("Location: http://personal-dash/index.php"); 

Hu: login.validate-redir,test.php is the page # that users are redirected to, after clicking “Login” from the login.php; this page will later include some validation functions, and a re-direct back to login.php<Turing!> if the validation is not passed; here, however, it will just # assign the $_POSTed ‘username’ to $_SESSION[‘username’], and redirect users back to the homepage.

H3S2: session_start():

Hu: From my testing, a page # will return an error, if I attempt to use the $_SESSION[‘username’], as in:

	if ($_SESSION['username'] == $post_author_username) {

Hu: without session_start(); preceding. However, it’s possible, that # when an inclusion page contains session_start();, that subsequent.chain-docs that require it will adopt the action of that function<Turing> as well.

H4S1: Double-start:

Hu: The above error # occurs when we have 2 session_start(); statements in a row, in the same document, or an activated | include already contains session_start();, and we have a second instance, in the calling | document. This error, incidentally, also confirms that session_start(); does propagate from a calleddoc.

H4S2: Use of $_SESSION requires session_start():

Hu: Tested in mysql.select-order,test.php.

H3S2: session_destroy():

H4S1: Basic logout implementation:

X.ref-WP,MIC.H2S10-H3S8,H4S5.H5S51:

session_start();
session_destroy();
require 'C:\wamp64\www\personal-dash\php_local_libs\testing-inc.php'; 
sess_super_username_check(); 
header("Location: http://personal-dash/index.php");

Hu: This page will # destroy a session when it’s loaded, and redirect users, back to the home | page.

H4S2: Only a page that contains session_start(); can session_destroy(); #

References:

Dani-Krossing “5:17 Change content with PHP when users are logged in – PHP tutorial”
Krossing: 2.hr-tut
Krossing: Sessions and Cookies in PHP

https://kinsta.com/blog/wordpress-cookies-php-sessions/

https://wordpress.stackexchange.com/questions/49909/why-does-wordpress-need-two-cookies-for-auth-login

https://kinsta.com/knowledgebase/wordpress-salts/

Sample code: 
<?php if ( is_user_logged_in() ) { ?>
    
<a href="<?php echo wp_logout_url(); ?>">Logout</a>
<?php } else { ?>
    
<a href="/wp-login.php" title="Members Area Login" rel="home">Members Area</a>
<?php } ?>

WordPress Cookies and PHP Sessions – Everything You Need to Know

https://smartwp.com/check-if-user-is-logged-in-wordpress/

https://www.php.net/manual/en/function.session-start.php

Issues:

Hu: Sometimes, behavior is consistent, upon multiple refreshes; a particular name might be displayed, as $_SESSION[‘username’]; and subsequently $_SESSION[‘username’]; might become undefined, in the next refresh, but the script on page does not reflect this behavior #


Leave a Reply

Your email address will not be published. Required fields are marked *