Search code examples
phpsetcookie

How to set country location and other variables to a cookie with php


I want to set a cookie with the country name and city location but I am unable as we had to set cookies before anything. How can I set my variables to its value?

include_once('ip2locationlite.class.php');
$ipLite = new ip2location_lite;
$ipLite->setKey('d930e8b9b1a38e8f647a5f22cce63e18a414e99aaf329a9f38a6caf8f623ec31');
$locations = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
$errors = $ipLite->getError();
$values="";
if (!empty($locations) && is_array($locations)) {
echo $locations['ipAddress'];
echo $locations['countryName'];
echo $locations['regionName'];
echo $locations['cityName'];
$values="ipaddress : ".$locations['ipAddress']."<br>country : ".$locations['countryName']."<br>region : ".$locations['regionName']."<br> city :".$locations['cityName'];

}

if(!isset($_COOKIE['trakcer']))
{
    setcookie('trakcer',$values);
}

Solution

  • \you are using wrong way to set cookie, try:

    if (!empty($locations) && is_array($locations)) {
    $values = serialize($location); //serialize you array
    //then set cookie
     if(!isset($_COOKIE['trakcer'])) {
       setcookie("CookieName", $values, time()+3600);  /* expires in 1 hour */
     }
    }
    //and to get it
    $array = unserialize($_COOKIE['CookieName']);