I tried to read a PHP cookie but I couldn't, although I was able to see it in the Chrome console. I have found the solution myself, using debugging methods, but in case someone else is having the same problem, I'll answer this question myself, in order to save you time.
I was using this code:
if(!empty($_COOKIE['my.cookie'])) {
echo "cookie value: ".$_COOKIE['my.cookie'];
}
// fallback
else {
echo "cookie not set!";
}
Using the var_dump() function helped me identify the problem, because the cookie-name was changed by PHP, automatically. (Maybe a bug, or some kind of known limit - my version is PHP 7.0.33.)
var_dump($_COOKIE);
This resulted in the list of cookies printed on the web page, and the cookie name was changed from "my.page-LANG" to "my_page-LANG".
So I renamed my cookie and I was good:
if(!empty($_COOKIE['my_cookie'])) {
echo "cookie value: ".$_COOKIE['my_cookie'];
}
// fallback
else {
echo "cookie not set!";
}
Related
i want to include cookies in my website in php but i don't know how to do this.
i've tried to include them with sessions but it didn't work.
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
i expected to keep me connected but it didn't. What else do i need to add in my code to make this work?
You're looking for setcookie()
Take a look at the PHP documentation for examples.
Edit:
To explain, before you can read a cookie, you need to set the cookie somewhere. You must call setcookie() before you output any information (e.g. echo or html before the php script tags) or there will be an error.
setcookie() also does not determine whether a user accepted the cookie. If a user has cookies disabled in browser, you would not be able to set or retrieve a cookie.
Since cookies can be manipulated, they tend to be a very bad place to store whether a user is logged in. Generally, sessions are better for that.
I am working on this CodeIgniter project, and I want to provide the 'Remember Me' feature for logging in. and for that I am setting a cookie like this.
if(strtolower($loggedin) == 'on') {
//set cookie for 30 days.
setcookie('teacher_login', $teacher_id, time()+60*60*24*30);
}
redirect();
I have checked by using,
echo setcookie('teacher_login', $teacher_id, time()+60*60*24*30);
and the output was '1'. But after the redirect to the home controller, there when I check use the following:
if (isset($_COOKIE["teacher_login"])) {
echo $_COOKIE["teacher_login"];
} else {
echo 'cookie not set';
}
and the output here is 'cookie not set'.
I don't know what is going on here, I checked the PHP manual and the instructions seemed simple enough. Moreover I tried to use the CodeIgniter cookie helper. set_cookie($cookie) didn't work either.
What could possibly be the problem?
I am new to PHP. I want to implement PHP session manually. On a PHP pageload, I will check if cookie is set. If yes, I will display the required information, and if not, I will ask user to enter his details and then display the information. But I am not allowed to use PHP Sessions. I can use Cookies. Also the information needed to be displayed is about all the users (browsers) who are in session (so I have to save this to some static global array). Any help is appreciated. Thanks.
try this
setcookie('cookie_name', 'cookie_value', time());
echo $_COOKIE['cookie_name'];
Now check the cookie if it exists.
if(isset($_COOKIE['cookie_name'])) {
echo "your cookie is set";
} else {
echo "return error or any thing you want";
}
This will give you all browser(s) information.
echo $_SERVER['HTTP_USER_AGENT'];
I've been working with PHP sessions, and everything is working fine it does exactly what I need.
Then I started to look into potential security issues further and found this:
http://phpsec.org/projects/guide/4.html
Notice that all that was being used was to determine existing session or new session 'status' is:
session_start();
...and yet I have seen this sort of thing many times before:
<?php
if (isset($PHPSESSID))
{
session_start($PHPSESSID);
}else{
session_start();
};
?>
I had assumed that this would allow some other processing on second call or that it's logic allowed the session to restart with the same session ID for a different page for example.
However I already thought that the plain session_start() already had logic to determine if a session had been established elsewhere because it 'knows' to retain an existing session ID rather than issuing a new one, unless it needs to of course!
So I tested the above and I couldn't get it to work at all.
<?php
if (isset($PHPSESSID))
{
$oldsession = "On";
$newsession = "Off";
session_start($PHPSESSID);
}
else
{
session_start();
$newsession = "On";
$PHPSESSID = session_id( );
};
echo 'ClientSessionID : '.$PHPSESSID.'<br>';
echo 'Refreshed Session : '.$oldsession.'<br>';
echo 'New Session : '.$newsession.'<br>';
?>
Either I'm missing something or this code could never have worked. The $oldsession NEVER gets echo'ed even though the session is retained. I conclude that the test on $PHPSESSID never works.
So my question is: Assuming the sample test code is syntactically correct, is it even plausible to attempt to pre-determine the session 'status' BEFORE calling session_start() ? And if so how would you go about it?
As the article goes on to show, using the (assumed) resulting session variables after a session has started is the only way to send the code in a different direction, so I'm thinking this is actually the only way to do it.
It looks like the article was written in early 2005, so perhaps the article was assuming that the register_globals setting was turned on. Earlier in PHP4, it was on by default, but it has been disabled by default in PHP5.
For your code to work, you'd need to explicitly use $_GET['PHPSESSID'] or $_COOKIE['PHPSESSID'], since the global variable $PHPSESSID is probably not set due to register_globals being disabled.
Also, note that the session name won't always be "PHPSESSID." That's default, but it can be changed in the session.name server setting or changed in the code at runtime with session_name().
session_start() will reclaim an active session if one exists. You can observe this behaviour with the following snippet:
<?php
session_start();
echo 'Current session ID: ' . session_id();
$_SESSION['previous_id'] = session_id();
session_regenerate_id();
echo '<br />Session ID on next execution: ' . session_id();
if(isset($_SESSION['previous_id']))
echo '<br />Session ID on previous execution: ' . $_SESSION['previous_id'];
?>
Wiseguy said the rest.
Your if(isset($PHPSESSID)) isn't checking what you think it is. I'm not sure of the syntax off hand... but try this:
<?php
if (isset(session_id($PHPSESSID)))
{
$oldsession = "On";
$newsession = "Off";
session_start($PHPSESSID);
}
else
{
session_start();
$newsession = "On";
$oldsession = "None";
$PHPSESSID = session_id( );
};
echo 'ClientSessionID : '.$PHPSESSID.'<br>';
echo 'Refreshed Session : '.$oldsession.'<br>';
echo 'New Session : '.$newsession.'<br>';
?>
I also added a value to $oldsession so that you can see that $PHPSESSID isn't 'set'.
Hope that helps!
Good luck!
Thanks Dae and Wiseguy, you answers gave me the hint I needed although what you didn't mention was the security aspect which was what brought me to the subject.
To put in context the examples I had seen undoubtedly were legacy code from a time when register_globals was switched "on" by default, and obviously had not been updated.
The reason why the code cannot work now is that regsiter_globals has been switched off as a default setting in PHP for security reasons. As of 5.3.0 it has been deprecated and I was working with 5.3.4
The security issue I was looking at was a method to determine the if the user who was using the session was the original user and not someone spoofing their session, and some of the information (IP address) could be available in the header even before you decide to start the session.
But I learn now that the IP address can also be spoofed, and therefore I think that starting the session first and (recovering any previously set session variables) validate after.
As in the original article!
I am looking for some code that will return me values if the user has JavaScript enabled or disabled, as well as cookies.
I know this is probably easy to do, but my time constraints are so tight, it hurts. There has to be something out there using php that does this. Ideally I would love to find code that has a page setup with all the possible values that could affect my scripts.
EDIT: Obviously JavaScript may be disabled, but, I am hoping that I can find something out there to test the two cases.
My Solution
For anoyone else looking for code to detect if the users has cookie enabled or disabled, here is what I ended up coming up with from the posts below... you can just drop this at teh top of any page and it works...
<?php
// do a cookie test
if (!isset($_SESSION['cookie_check']))
{
if (!isset($_GET['cc']))
{
// drop a cookie in their bag
setcookie("cookiecheck", "ok", time()+3600);
header("Location: ".$common->selfURL()."?cc=1");
exit(0);
}
else
{
// do we have a problem?
if (#$_COOKIE['cookiecheck'] != "ok")
{
// we have a problem
header("Location: /site-diag.php");
exit(0);
}
else
{
$_SESSION['cookie_check'] = true;
}
}
}
?>
You could use the jQuery cookie plugin to write a cookie and then see if you can read it back again. That would tell you if cookies were enabled in the client's browser or not.
For checking Javascript, either they have it or they don't. If not, you can use <noscript> tags to display a message asking them to turn it on, put a meta redirect inside, etc. That is the extent of your testing ability.
As for cookies, just try setting a cookie then reading it back! Since you're concerned about Javascript's ability to handle cookies, I assume you already have a cookie library that you are using, meaning that you can just use the set function for a test cookie then the get function to read it back. If the test cookie can't be read back, cookies are off.
Here is one for checking cookies
http://techpatterns.com/downloads/javascript_check_cookies.php
if javascript is disabled then you can't use jquery or prototype.
write a function that writes a cookie, then tries to read it.
and secondly puts out some js code to the screen that makes a ajax call to a basic php script.
you can use a database to set the boolean results of both tests on the visitor table if there is one.
This is the way I check if cookies and JavaScript are enabled:
if($_SESSION['JSexe']) { // 3rd check js
if($_COOKIE['JS']) {
setcookie('JS','JS',time()-1); // check on every page load
}
else {
header('Location: js.html');
}
}
// 2nd so far it's been server-side scripting. Client-side scripting must be executed once to set second cookie.
// Without JSexe, user with cookies and js enabled would be sent to js.html the first page load.
elseif($_COOKIE['PHP']) {
$_SESSION['JSexe'] = true;
}
else { //1st check cookies
if($_GET['cookie']) {
header('Location: cookies.html');
}
else{
setcookie('PHP','PHP');
header('Location: '.$_SERVER['REQUEST_URI'].'?cookie=1');
}
}
Explained in detail here: http://asdlog.com/Check_if_cookies_and_javascript_are_enable
First, realize that you can't use JavaScript to check for cookies if JavaScript is turned off. The usual check for cookies being on is to write one and then read it.
Do you care about the case when cookies are on but JavaScript is off? What are you going to do based on the information?
I found this code here for checking for a cookie via PHP. Doesn't rely on JavaScript. Is PHP your server language?
<?php
class cookieCheck
{
public function check()
{
if (setcookie("test", "test", time() + 100))
{
//COOKIE IS SET
if (isset ($_COOKIE['test']))
{
return "Cookies are enabled on your browser";
}
else
{
return "Cookies are <b>NOT</b> enabled on your browser";
}
}
}
}
?>