user4345221
user4345221

Reputation:

php regex - cookie name

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!

Upvotes: 4

Views: 2244

Answers (2)

Forien
Forien

Reputation: 2763

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);

Upvotes: 7

Deep
Deep

Reputation: 2512

function keyLike(array $arr, $like)
{
    foreach (array_keys($arr) as $k) {
        if (preg_match($like, $k)) {
            return true;
        }
    }

    return false;
}
...
if (keyLike($_COOKIE, '/^cookie_.+/')) { ...

Upvotes: -1

Related Questions