Here i have an if else that create cookie with name check_CookiesRW and with content randomly generated by rand(1000,999999);. I would love to check if the cookie content randomly generated and stored on $_SESSION would match and echo out Cookie is SET something like this
if(isset($_COOKIE['check_CookiesRW']) && $_COOKIE['check_CookiesRW'] === $_SESSION['cookie_content'])
how can i achieve this without it throwing out error Warning: Undefined variable $_SESSION ??
<?php
if(isset($_COOKIE['check_CookiesRW'])) {
print "<h1>Cookie is SET</h1>";
} else {
$cookie_name = "check_CookiesRW";
$cookie_content = rand(1000,999999);
$_SESSION['cookie_content'] = $cookie_content;
setcookie($cookie_name, $cookie_content, time()+30, "/");
print "<h1>Created Cookie</h1>";
}
?>
Related
I am attempting to set a value into the $_SESSION super global in the page set.php
this the snippet :
if (isset($_POST['sales']) && $_POST['sales'] != ""){
$sales = sanitize_input(trim($_POST['sales']));
$_SESSION['nam0'] = $sales;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'access.php';
header("Location: http://$host$uri/$extra?so=".$sales);
exit();
}
and to access the value stored in $_SESSION['nam0'] in access.php like this:
<?php
/*To check availbality of SOs for given Sales Order Number in so.php*/
// Initialize session
session_start();
$SD_ID = $_SESSION['nam0'];
However, I am hitting the following error:
Notice: Undefined index: nam0 in access.php on line 7
I don't know why. Can someone help me on this? Thanks a lot.
Session are used like this:
<?php
session_start();
echo $_SESSION['key'] ?? 'key not found';
You can always dump the contents of the session array by doing var_dump($_SESSION);.
I'm guessing that you havn't set your index (submitted the form) yet and therefore getting a "Undefined Index".
I have created the session on the login page and stored in a variable.
on the Login page
$_SESSION['user_id'] = $id;
Now I want to check session that exists or not?
On other pages
<?php
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
You need to call
session_start();
on top of file to start the session.
To set a value,
$_SESSION['user_id'] = 1;
To check if session exists and not empty
if(!empty($_SESSION))
{
// write code here
}
To check for a particular value is set
if(isset($_SESSION['user_id']))
{
// write code here
}
You can use isset
if (isset($_SESSION['user_id'])) {
echo 'Session is active';
}
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
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!";
}
This is in a page called headersessioncookie.php
<?php
session_start();
if ( ! isset ( $_SESSION['loggedin'] ) ) {
$_SESSION['loggedin'] = FALSE;
}
$expiry = time()+60*60*9000;
setcookie('cookie[loggedin]', '', $expiry, "", "", "", TRUE);
if ( ! isset ( $_COOKIE['cookie[loggedin]'] ) ) {
$_COOKIE['cookie[loggedin]'] = FALSE;
}
?>
This is in a page called test.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
$_SESSION['loggedin'] = TRUE;
$_COOKIE['cookie[loggedin]'] = TRUE;
?>
When I run test.php and then run this page below called test1.php ...
<?php
require_once('headersessioncookie.php'); //start session and cookie
echo "sessionvalue" . $_SESSION['loggedin'] . '<br>';
echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';
?>
... I get
sessionvalue1
cookievalue
Why don't I get...
sessionvalue1
cookievalue1
...??
The superglobal variable $_COOKIE only contains the cookie values. If you modify this value won't affect to the cookie because you need to sent the headers to the browser to do so.
If you need to modify it you have to use the method setCookie because this will sent the headers with the new value.
Note Remember that the $_COOKIE only will be updated after use setCookie when you refresh the page.
So this should work:
File: headersessioncookie.php
<?php
//Session
session_start();
if ( !isset($_SESSION['loggedin']) )
$_SESSION['loggedin'] = FALSE;
//Cookie
$expiry = time()+60*60*9000;
if ( !isset($_COOKIE['cookieloggedin']) )
setcookie('cookieloggedin', '', $expiry, "", "", true);
?>
File: test.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
$_SESSION['loggedin'] = TRUE;
setcookie('cookieloggedin', '1', $expiry, "", "", true);
?>
File: test1.php
<?php
require_once('headersessioncookie.php'); //start session and cookie
echo "sessionvalue" . $_SESSION['loggedin'] . '<br>';
echo "cookievalue" . $_COOKIE['cookieloggedin'] . '<br>';
?>
Please notice also:
-How to update a cookie: https://stackoverflow.com/a/6487597/3933332
-Is a Cookie Case Sensitive: https://stackoverflow.com/a/11312272/3933332
Answering my own question. Turns out there were 3 major problems with my code.
1) I was trying to set the cookie value by doing this:
$_COOKIE['cookie[loggedin]'] = FALSE;
Turns out one needs to use setcookie() to set the cookie value. Assigning a new value to $_COOKIE will change the value of that variable (within the scope of the same page), but it won't change the value inside the cookie (outside the scope of that page, calling $_COOKIE will yield the value stored in the cookie).
2) The following is incorrect
echo "cookievalue" . $_COOKIE['cookie[loggedin]'] . '<br>';
Instead it should be
echo "cookievalue" . $_COOKIE['cookie']['loggedin'] . '<br>';
3) Cookie necessarily has to be passed a string value. I was trying to pass a value = FALSE which is not a string. Instead, I could have correctly passed a value = 'FALSE'