Jump to content

find dynamic cookie name


pwfans
 Share

Recommended Posts

You'll have to look through the $_COOKIE superglobal to find the cookie name that matches your format. You can do that with regular array functions. For example:

// just for testing
$_COOKIE['name_xyz'] = 'Test value';
$_COOKIE['name_foo'] = 'Bar';

$cookieNames = array_filter(array_keys($_COOKIE), function ($key) {
	// check if the cookie name starts with "name_"
    return preg_match('/^name_/', $key) === 1;
}));

print_r($cookieNames);
// -> Array ( [6] => name_xyz [7] => name_foo ) 

print_r($_COOKIE[current($cookieNames)]);
// -> Test value

Adjust the preg_match pattern to match the pattern you're looking for. The result will be an array of keys that match your format. Note that this array is NOT zero-indexed, because array_filter doesn't change the keys, hence the use of current to get the first value. Alternatively, use array_values to zero-index the array, or foreach to loop through all matching cookies.

If you dislike the raw use of $_COOKIE, you can also use $input->cookie()->getArray() (docs).

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...