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" ?????
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[]
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";
}
}
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];
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
Related
I want to get cookie's name in PHP. Not cookie's value! My code like below:
<?php
session_start();
ob_start();
$user_id = $_GET["user_id"];
$timing_clock = "";
if(isset($_COOKIE["timing_type"])){
// cookie's value
$timing_clock = setcookie("timing_type");
// how to get cookie's name?
} else {
echo("0");
}
?>
How can i do that? I want to set cookie's name to a variable. Because cookie's name are very important for me.
it will help you, use var_dump($_COOKIE) and get all COOKIE name.
$cookie_name = "user";
$cookie_value = "Dave";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
if(isset($_COOKIE)) {
var_dump($_COOKIE);
foreach($_COOKIE as $key => $val)
{
echo "cookie name = ".$key.", and value = ".$val;
}
}
This will print all with respective name
<pre>
<?php print_r($_COOKIE); ?>
</pre>
In this example
setcookie("timing_type");
the cookie name would be $_COOKIE['timing_type']
When you use the setcookie function you are applying the cookie name(key).
All cookies names are stored in $_COOKIE as "Name" => "value".
Simply output the keys of the $_COOKIE array and you'll have your names :)
Simply read $_COOKIE["name"] to get the name set by setcookie
The first paramater of setcookie() is the name of the cookie
<?php
session_start();
ob_start();
$user_id = $_GET["user_id"];
$timing_clock = "";
if(isset($_COOKIE["timing_type"])){
// cookie's value
$timing_clock = setcookie("timing_type");
// how to get cookie's name?
$cookie_name = $_COOKIE['timing_type'];
} else {
echo("0");
}
?>
$_COOKIE["name"] = "JASON STATHAM";
I am trying to unset the cookies, I had earlier set as:
setcookie(session_name(),$sessionID,time() + 30*24*3600,'/');
setcookie('UserID',$result[0]['UserID'],time() + 30*24*3600,'/');
setcookie('UType',$result[0]['UType'],time() + 30*24*3600,'/');
setcookie('Username',$Username,time() + 30*24*3600,'/');
Logout File:
function unsetCookie() {
foreach($_COOKIE as $key => $value) {
// $_COOKIE[$key] contains the cookie name as expected
setcookie($_COOKIE[$key],'',time()-(40*24*3600),'/');
}
}
unsetCookie();
session_start();
session_destroy();
header('Location: '.$loginPage);
exit();
But after the redirect in the logout file, cookies are still not deleted. What could be the reason for this?
$_COOKIE[$key] contains the value of your cookie, not the key as that is $key.
So you would need:
setcookie($key,'',time()-(40*24*3600),'/');
Set the value to "" and the expiry date to yesterday (or any date in the past)
Try this code like that :-
setcookie("UserID", "", time()-(40*24*3600));
setcookie("UType", "", time()-(40*24*3600));
setcookie("Username", "", time()-(40*24*3600));
I am trying to destroy a session when a session is selected but it is not being destroyed:
if (isset($_POST['primary_cat'])) {
$_SESSION['primary_cat'] = $_POST['primary_cat'];
unset($_SESSION['secondary_cat']);
}elseif(empty($_SESSION['primary_cat'])) {//define primary_cat
$_SESSION['primary_cat'] = null;
}
When I change $_POST['primary_cat'] this is changed but $_SESSION['secondary_cat'] is not being destroyed. How can I destroy $_SESSION['secondary_cat']
This is how I completely destroy the one and only session I have:
session_start();
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params["path"],$params["domain"], $params["secure"], $params["httponly"]);
echo " Zerstöre Cookie... ";
}
#session_unset();
#session_destroy();
Maybe it helps you to adapt your code for your specific session.
if (isset($_POST['primary_cat'])) {
$_SESSION['primary_cat'] = $_POST['primary_cat'];
unset($_SESSION['secondary_cat']);
} elseif (empty($_SESSION['primary_cat'])) {//define primary_cat
$_SESSION['primary_cat'] = null;
}
You should try these instead:
if (isset($_POST['primary_cat'])) {
session_destroy();
$_SESSION['primary_cat'] = $_POST['primary_cat'];
} else if (!$_SESSION['primary_cat']) {
//your business
}
An explanation to that is on clicking or selecting
"primary_cat"
it should run that block of code else it won't run that code and if it does, you the
session_destroy();
Destroys active session and the below creates a new session due your specifications.
Your code seems ok, problem might be from your browser.
make sure session is started. if it's still not destroyed, then close your browser and restart apache.
But also make sure you are not setting $_SESSION['secondary_cat'] somewhere else your code.
To be sure, do the following after unsetting $_SESSION['secondary_cat']
if(isset($_SESSION['secondary_cat'])){
echo '<script type="text/javascript">alert("the session still has value : '.$_SESSION['secondary_cat'].'");</script>';
}
else
echo '<script type="text/javascript">alert("session has been unset");</script>';
The above will display a javascript alert showing "the session still has value : thevalue" if the session was not unset or "session has been unset" if it really has been unset
hope this helps
try this...
if(isset($_SESSION['secondary_cat'])&&!empty($_SESSION['secondary_cat'])){
unset($_SESSION['secondary_cat']);
}
What's the correct way of passing variable using PHP cookie. I can't seem to get it to work? I keep getting "FAILED!"
Here's my code:
On 1st page:
$crpid['ONE']="PAGE1";
$crpid['TWO']="PAGE2";
$crpid['THREE']="PAGE3";
$crp_id = $_SERVER["REDIRECT_URIPART"];
$crp_value = $crpid[$crp_id];
session_start();
setcookie('crpid', $crp_value, time()+3600, "/");
On 2nd page:
if(!isset($_COOKIE['crpid']) && $_COOKIE['crpid']==''){
echo "FAILED!";
}
else{
echo "Cookie ".$_COOKIE['crpid']." is set!";
}
I do the following to set my session, this works because the echo appears. but when I go to the next page or another the session is not there? what am I doing wrong?
$session_start();
if ($username==$dbusername&&$password==$dbpassword)
{
echo"<b>Login Successful</b><br><a href='systemadmin.html'><br>Click here to access the <strong>System Admin Page</strong></a>";
$_session['username']=$dbusername;
if($username == "admin")
{
$_session['admin'] = true;
}
I am trying to get the following to work with these sessions:
<?php
session_start();
if($_session['admin'] == true)
{
// do nothing
}else{
header( 'Location: home.html' ) ;
}
?>
Update:
the uppercase sessions work but now the sessions arent destroying when i use the logout.php
<?php
session_start();
session_destroy();
header("location: home.html");
?>
$_session should be => $_SESSION.
http://php.net/manual/en/reserved.variables.session.php
The first works because you are setting a 'normal' variable (which is available for the request).
UPDATE
To destroy the session:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
http://php.net/manual/en/function.session-destroy.php#example-4368
Additionaly you should always use exit(); after you do a redirect to prevent further execution of the script.
PHP Server/Session/Global variables are case sensitive. To PHP, $_SESSION is NOT the same variable as $_session, even though to you in English, they seem to be. You must use $_SESSION, not $_session in order to access the PHP Session variables as you are expecting.
You have to use exit(); after the header(); because the script doesn't always end right after the user redirects to a new page.
The name of the superglobal is $_SESSION in uppercase letters. Try changing that and see if it helps.