Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php regex - cookie name

Tags:

regex

php

cookies

i need help again. I have to code a function that gets me the cookie. but i only knows part of the cookie name. I got a JavaScript-Function that's working very well:

function readCookie(cookiePart){            
            var results = document.cookie.match(cookiePart + '(.*)=(.*?)(;|$)');            
            if(results){
                var result = results[0].replace(cookiePart,''); 
                var cookie= result.split("="); 
                return(cookie[0])           
            }else{
                return null
            }
        }           
        alert(readCookie("cookie_"));

I try to code the same for PHP. But still stuck:

$cookie_name = "cookie_";   
    if(!isset($_COOKIE["$cookie_name" . "/^*$/"])) {
        echo "Cookie named '" . $cookie_name . "' is not set!";
    } else {
        echo "Cookie '" . $cookie_name . "' is set!<br>";       
    }

i think i do the regex part wrong. maybe you can help me where to add it? i tried on the varaiablename when define or match, but nothing works.

thx for any hint my friends!


1 Answers

Problem

The thing is, that in JavaScript you used a method .match() for regexp, but you didn't use anything for regexp in PHP.

And you cannot that easily match keys, you can only do this when iterating over entire array.

But you don't have to use regexp to achieve what you need.

Solution

I recommend this:

$set = false;
$cookie_name = 'cookie_';
foreach ($_COOKIE as $name => $value) {
    if (stripos($name,$cookie_name) === 0) {
        echo "Cookie named '$name' is set with value '$value'!";
        $set = true;
    }
}
if (!$set) {
    echo 'No cookie found :(';
}

Will list all valid cookies (having names beginning with "cookie_"), or display sad message.

And I think that if you can achieve something relatively easy without regex, you should.

If you need to use cookie names afterwards

Use this modified code:

$cookie_name = 'cookie_';
foreach ($_COOKIE as $name => $value) {
    if (stripos($name,$cookie_name) === 0) {
        $cookies[] = $name;
    }
}

And you have now table $cookies that contains names of every valid cookie set. If you need only part that's after _ then use this line instead:

$cookies[] = str_replace('cookie_','',$name);
like image 166
Forien Avatar answered Oct 18 '25 09:10

Forien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!