'How to get cookie value
Creating cookie
session_start();
$params = session_get_cookie_params();
setcookie(session_name('USERNAME'),'HAMZA',1,
isset($params['path']),
isset($params['domain']),
isset($params['secure']),
isset($params['httponly']));
session_regenerate_id(true);
echo "COOKIE IS CREATED SUCCESSFULLY !";
Now fetching cookie value
session_start();
$NAME=$_COOKIE['USERNAME'];
echo $_COOKIE["USERNAME"];
if(isset($NAME))
{
if($NAME=='USERNAME')
{
echo "success";
}
else
{
echo "error";
}
}
Please Help Me !
Result
Why they create Auto random Value Like: u8omuum6c9pkngrg4843b3q9m3). But i want to get my Original COOKIE value Which is "HAMZA" ?????
Solution 1:[1]
This is the PHP syntax for cookie creation:
setcookie($name, $value, $expires, $path, $domain, $secure, $httponly);
The first variable is your cookie name, which you can use to read the value like this:
$_COOKIE['YOUR COOKIE NAME'];
Note: Like other headers, cookies must be sent before any output from your script. This requires that you place calls to this function prior to any output, including <html> and any whitespace.
Also note that dots and spaces (./ ) in cookie names are replaced with underscores (_).
Documentation: setcookie(), $_COOKIE[]
Solution 2:[2]
Function session_name will give you hash which atucally is you session identifier. It seems like you want to get USERNAME stored in session, don't you? In that case you should use $_SESSION array.
Code example:
setcookie($_SESSION['USERNAME'],'HAMZA',1,
isset($params['path']),
isset($params['domain']),
isset($params['secure']),
isset($params['httponly']));
And you can get it like this:
$myCookie = $_COOKIE[$_SESSION['USERNAME']];
But from your second code it's not quite clear what you want to get. If you want to ask for $_COOKIE['USERNAME'] and get 'HAMZA' then you should set it like this:
setcookie('USERNAME','HAMZA',1,
isset($params['path']),
isset($params['domain']),
isset($params['secure']),
isset($params['httponly']));
And when you retrieve it $NAME=='USERNAME' makes no sense, because it will be like $NAME=='HAMZA':
$NAME=$_COOKIE['USERNAME'];
echo $_COOKIE['USERNAME'];
if(isset($NAME))
{
if($NAME=='HAMZA')
{
echo "success";
}
else
{
echo "error";
}
}
Solution 3:[3]
try this one ...
<?
$yummy = json_decode(json_encode($_COOKIE));
if(isset($yummy->yourvar)) echo $yummy->yourvar;
?>
Why using encode and decode ?, it use to convert type Array to JSON originally type $_COOKIE is Array
Solution 4:[4]
try this one ...
setcookie($cookie_name, $cookie_value, 1800, "/");
change expires time with:
setcookie($cookie_name, $cookie_value, time()+ 1800, "/");
and get
$_COOKIE[$cookie_name];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | isherwood |
| Solution 2 | Djengobarm |
| Solution 3 | |
| Solution 4 |
