caner taşdemir
caner taşdemir

Reputation: 203

Php - Search a string in cookie

I set cookie with php, using

setcookie("name", "John Mayer", time()+31556926 , "/");

After, I want to search Cookie value with php to check if it includes a value, using

if (strpos($_COOKIE["name"],"Mayer")) {

However, it always returns false. Is it not allowed to check cookie value with php ? If so is there anyway to check it ?

Upvotes: 1

Views: 1158

Answers (4)

Veshraj Joshi
Veshraj Joshi

Reputation: 3579

Actually strpos returns a index so,if string matched from initial then it returns 0 which is zero and considered as false. It returns -1 if search text didnot matched, so you can make a condition like-

  if (strpos($_COOKIE["name"],"Mayer")>=0)
  {

  }
  // or strict comparison with false
  if (strpos($_COOKIE["name"],"Mayer")!==false)
  {

  }

Upvotes: 2

deviantxdes
deviantxdes

Reputation: 479

check if its set and proceed

    if(isset($_COOKIE["name"])) {

if (strpos($_COOKIE["name"], 'Mayer') !== false) {
    // it exists
        echo 'true';
    }

    }

Upvotes: 1

Văn Tuấn Phạm
Văn Tuấn Phạm

Reputation: 659

You edit your code.

 if(isset($_COOKIE["name"]) && !empty($_COOKIE["name"])) {
    if (strpos($_COOKIE["name"], 'Mayer') !== false) {
      echo 'exists';
    }
}

Upvotes: 1

AndreFeijo
AndreFeijo

Reputation: 10629

Change it to:

if (strpos($_COOKIE["name"],"Mayer") !== false) {

PHP strpos manual

Upvotes: 1

Related Questions