Welcome Guest, Not a member yet? Register   Sign In
Using Session Variables in Routes

(This post was last modified: 06-07-2022, 09:03 AM by AgBRAT.)

I have a project where members can create an account, upload images, subscribe to other members, like/dislike/comment/etc. on images, and view other member profiles. 
I am running into an issue where I cannot use session variables in my routes. I am trying to do this by passing parameters to my controllers for logged in user's profile page that is also used for other user's profile page. This use to work before I switched $routes->setAutoRoute(FALSE).
For example: http://localhost/users/profile/{session(...username')} and http://localhost/users/profile/{$otherUser} would use the same Controllers and Views just different URI segments.
I have read that you cannot use session variables in routes because they are initialized after the routes have already been constructed. Is there anyway around this such as through Events or Hooks? If so how do I implement that? I am fairly new to CodeIgniter 4 and teaching myself PHP as I go (though a little more familiar). So please be kind if this is a stupid question.
Here is some of my code starting with the View '\App\Views\templates\header.php' view where I need the route:
PHP Code:
<a href='<?= route_to('member_profile', session()->get('username')); ?>' title='My Profile'>My Profile <class='fas fa-user-edit dropdown-icon' style='color:black'></i></a>

a href='<?= route_to('member_profile', $row->uploader);?>' title='<?= $row->uploader . "'s Profile"; ?>><?= esc($row->uploader); ?></a> 

Here is my '\App\Config\Routes.php':
PHP Code:
$routes->get('profile/(:segment)''Users\Members::profile/$1', ['as' => 'member_profile']); 

Here is an excerpt of my Controller '\App\Controllers\Users\Members.php:
PHP Code:
public function profile(string $user)
        $data = [];

        if (session()->get('username') == $user) {

            $data = [
                'title'        => 'My Profile',
                'editProfile'  => TRUE,
} else {

            $data = [
                'title'        => $user "'s Profile",
                'editProfile'  => FALSE,

        $data['profile'] = $this->profileModel->getUser($user);
        $data['userUploads'] = $this->imageModel->getImagesWhere(['uploader' => $user]);
        $data['userSubscribed'] = $this->subscribeModel->userSubscribed($user);
        $data['script'] = 'js/profile.php';

        echo view('templates/header'$data);
        echo view('templates/navigation'$data);
        echo view('users/profile'$data);
        echo view('templates/footer'$data);

Theme © iAndrew 2016 - Forum software by © MyBB