I want to pass a variable set by the user to the setcookie function.
I would like to let user change the color of some parts of website. so far the information about color is sent to server with $_SESSION['colorcode'] and I would like to add it to setcookie as well so when the user logs in to the site next time, his/her color is there.
I've got this code:
setcookie(
'colorcode',
$_SESSION['colorcode'],
time() + 60 * 60 * 24 * 30,
'',
'',
false,
true
);
I would like to save the value of variable in cookie, but it works just for the session.
what is wrong? how to do it so the color is there when the user logs in? I'm looking for another way than storing it in database or file.
Did you read back the value from the cookie at the beginning of the next session? Setting the cookie looks good but I think the last parameters could be omitted.
setcookie("colorcode", $_SESSION['colorcode'], time()+3600*24*30, '/');
Perhaps even the path ('/') is optional. But this only sets the cookie. You have to read the data back in, when the user returns to your site the next time.
if ( !isset($_SESSION['colorcode']) and isset($_COOKIE['colorcode']) ) {
if ( preg_match('/^#?[0-9a-fA-F]{6}$/', $_COOKIE['colorcode']) ) {
$_SESSION['colorcode'] = $_COOKIE['colorcode'];
} else {
// bad value... delete cookie if you like
}
}
When there is no colorcode in the session but the cookie-value exists, then the data is validated and if it's a valid 6 digit hex color code, then the value is inserted into the session. The validation is nessessary because a cookie is data that comes from the user and therefore potentially malicious.
This should work just fine:
setcookie("colorcode",$_SESSION['colorcode'],time()+60*60*24*30);
Just make shure you output it in the headers, I guess:
setcookie() defines a cookie to be
sent along with the rest of the HTTP
headers. Like other headers, cookies
must be sent before any output from
your script (this is a protocol
restriction). This requires that you
place calls to this function prior to
any output, including and
tags as well as any whitespace.
Do you get errors?
Try to check this:
setcookie('colorcode',$_SESSION['colorcode'],time()+60*60*24*30);
since cookie related functionalities (setcookie(), ...) work with HTTP headers, you should user them before any output is sent to client. but this does not mean these functions should appear at the beginning of your code. just make sure no output has been sent. even a single space character at beginning of your file outside of
Related
<!doctype html>
<html>
<head>
<title>Index</title>
</head>
<form action="newquestion.php" method="post">
Question <input type="text" name="question">
<input type="submit">
</form>
<body>
</body>
</html>
PHP file...
<?php
static $q = 1;
echo $q;
$q++;
?>
I'm new in PHP. Will this not increment $q by 1 each time "newquestion.php" is called? if not how to increment this variable each time this page(newquestion.php) gets called or opened?
No, because $q resets to 1 each time the page is called. You need some sort of persistence strategy (database, writing to a text file, etc) in order to keep track of the page views.
It's also a good idea to consolidate this functionality into a class, which can be used across your code base. For example:
class VisiterCounter {
public static function incrementPageVisits($page){
/*!
* Beyond the scope of this question, but would
* probably involve updating a DB table or
* writing to a text file
*/
echo "incrementing count for ", $page;
}
}
And then in newquestion.php,
VisiterCounter::incrementPageVisits('newquestion.php');
Or, if you had a front controller that handled all of the requests in your web application:
VisiterCounter::incrementPageVisits($_SERVER['REQUEST_URI']);
Every php script inside in a page is executed when you are loading this page. So everytime your script is executes line by line. You can not count page loading number by the process you are trying.
you can follow one of the process below:
1) you can save it to the database and each time when it is loading you can execute query to increment the count value.
2) you can do it by session like this:
session_start();
if(isset($_SESSION['view']))
{
$_SESSION['view']=$_SESSION['view']+1;
}
else
{
$_SESSION['view']=1;
}
The easy way is using a SESSION or a COOKIE based persistence methodology.
Using SESSION example:
In the beggining of the page (firt line prefered) put the following code:
session_start();
Check if a session for this user has been created and recorded, if so, increment by one the value of q session variable and display it.
If not, initialize q session variable with value 1, store and display.
if(!isset($_SESSION["q"]) //check if the array index "q" exists
$_SESSION["q"] = 1; //index "q" dosen't exists, so create it with inital value (in this case: 1)
else
$_SESSION["q"]++; //index "q" exists, so increment in one its value.
$q = $_SESSION["q"]; //here you have the final value of "q" already incremented or with default value 1.
//doSomethingWith($q);
Using COOKIE example:
$q = 0; //Initialize variable q with value 0
if(isset($_COOKIE["q"])) //check if the cookie "q" exists
$q = $_COOKIE["q"]; //if so, override the q value 0 with the value in the cookie
$q++; //increment in one the q value.
setcookie("q",$q); //send a HTTP response header to the browser saving the cookie with new value
//doSomethingWith($q);
//here you have the final value of "q" already incremented or with value 1 like in session.
With cookies, you cannot use $_COOKIE["index"] = value for set a value for cookie, you must use setcookie instead for that. $_COOKIE["index"] is only for read the cookie value (if it exists).
SESSION still use cookie, but only for identify that user is the owner of that session, the user cannot change the value of session directly (only if you provide a way to they do that).
Using COOKIE the user will see a cookie with name "q" and it's value and can easily change the value through simple javascript code, browser tools (like Google Chrome Developer Console Tool) or any extension for Browser (Edit This Cookie, a Google Chrome extension that list all cookies, values and parameters for a webpage).
Remeber that any session_start call (only one per page is necessary) or setcookie calls must be made before any buffer output like (but not just) echo, print. Because both calls produces a HTTP Header "Set-Cookie" and HTTP Headers must be sent before content body, calling this methods after a buffer flushing will throw a exception.
The two examples above are per user count. If you need a per application or per page count, you must implement a custom counter system, using file system to store data (the pageviews/page requests) or database to track individuals request (with date, ip address, page url, page name, anything else).
It won't work as you think. PHP code is executed each time from start to finish - meaning that no variables are kept over from one run to the next.
To get around this, you could use a session variable (this is a special sort of variable) which will keep a value in it that you could keep for each visitor to the site. This will however work for EACH VISITOR individually.
If you want to increment the value for all users (you open the first one, it says 1, I open the second it says 2 and so on) you will need to either store it in a database (good option), write it out to a text file (not really a good option) or magic up some other way to keep it saved.
Put $q initialization in any of your init page then increment the value.
or put the variable to increment in the session. with that, you could at least see, how often one user calls your pages.
The problem with your code is that the variable is first set to 1 each and everytime the page is visited. You will have to make use of $_SESSION. But then again the problem with using session variable would be that if you are trying to increase the value of your variable from different PCs or different systems, session would not work. For this the best thing will be to insert the value in database.
Alright I'm totally baffled.
Here's my code:
if ($password == $correct_password[0] && !isset($_COOKIE['user'])) {
setcookie("user", $email, time() + 3600);
var_dump(isset($_COOKIE['user']));
echo "!";
}
So it's doing the var_dumps, meaning that the setcookie should called. But the line right after it (checking if it's set) says it's not set!
If anyone could point out the problem it'd be greatly appreciated. Thanks
$_COOKIE is populated/loaded when the script first starts up, and then is NOT updated by PHP again for the life of the script. Setting a cookie via setcookie will only show up in $_COOKIE on the NEXT execution of the script.
This applies to all of the superglobals, except $_SESSION. They're populated/initalized at script startup and then PHP does not ever touch them again. $_SESSION is populated when you call session_start() (or sessions are set to auto start), which may be done multiple times within a script's lifetime.
PHP is a server-side language.
That means that it can generate whatever it wants and will then pass it to the client.
And that's it.
There is no back and forward on a single request.
1º you instruct the page 'A' to set a cookie
2º client recieves page 'A' and sets the cookie
3º client asks for page 'B' (sending the cookie)
4º server can identify the cookie (only on page 'B')
Page here is used as simple way of understanding a server call.
You can request the same page twice for the purpose.
Still didn't find a solid valid answer, but after endless hours of testing it seems like something with the time. If I set the expiration date too close to the real time, maybe it doesn't register or something. It seemed to work when I set the time further, but I'm taking a break before heavy testing again.
Thanks
When you use setcookie() it will save its value the next time that the HTML is loaded. If you want to see the vardump with the value you just assigned you will need to use $_COOKIE['cookie_name'] = $value;
I want to set a cookie via PHP. The scenario is like this:
Domain is: example.com
There is one web page on sub-domain (my.example.com). My code is:
$value="I am looged in";
setcookie("TestCookie", $value,'','',".example.com");
echo "hello".$_COOKIE["TestCookie"];
but the result is only "hello" - the cookie is not getting set.
First two corrections to the actual call of setcookie: Parameter 3 (expired) should be an integer value (the default value is 0); parameter four should be set to '/' to make the cookie valid for all subdirectories; the setcookie call should therefore look like this:
setcookie("TestCookie", $value, 0, '/', ".example.com");
Then it should actually work the second time the script is called. To understand why it won't work the first time already, we have to dig in a little into how cookies work; basically, Cookies are data sent from the server to the client, where the server says "send me this data the next time you send me a request". That's basically what setcookie is for: When the request is done and the client has received and processed the page, the cookie as specified will have been created at the client; $_COOKIE, on the other hand, holds all values which are in cookies already, and which have been transmitted by the client along with the request - meaning that the first time the script is called, $_SESSION will actually still be empty, since the cookies will only be created once the client has received the scripts output.
If I call setcookie() two times with the same cookie name, I get two cookies created.
How do you update an existing cookie?
You can update a cookie value using setcookie() function, but you should add '/' in the 4th argument which is the 'path' argument, to prevent creating another cookie with the same name.
i.e. setcookie('cookie_name', 'cookie_value', time()+3600, '/');
A suggested expiration time for the 3rd argument:
$exp_time = time()+3600; /* expire in 1 hour */
$exp_time = time()+86400; /* expire in 1 day */
You can't update a cookie per se, you can however overwrite it.
Otherwise, this is what you are looking for: http://php.net/manual/en/function.setcookie.php
It works. Be sure to read "Common Pitfalls" from that page.
You can use the super global $_COOKIE['cookie_name'] as well to read cookies.
Make sure there is no echo before setcookie call. setcookie communicates with browser through header, and if you called echo earlier, header+body is sent already and server cannot send setcookie to browser via header anymore. That is why you might see it is not working.
There should be a line like below in php server log file reporting warning in this case:
DEFAULT: PHP Warning: Cannot modify header information - headers already sent by (output started at /path/to/your/script.php:YY) in /path/to/your/script.php on line XX
So while PHP will send two Set-Cookie: headers if instructed so, only the last one should persist in browsers.
The Netscape cookie spec http://curl.haxx.se/rfc/cookie_spec.html says:
Instances of the same path and name will overwrite each other, with the latest instance taking precedence. Instances of the same path but different names will add additional mappings.
However, it might be advisable to avoid such edge conditions. Restructure your application so it doesn't need to override the already sent cookie.
call COOKIE and delete username value
SETCOOKIE("username",'',0,"/");
Here is the simple function that I'm using:
public function control() {
$string = 'lolcheck';
setcookie($string, $string, time() + 120, $this->path, $this->domain);
if (isset($_COOKIE[ $string ])) return true;
else return false;
}
The problem is that it only works when I open the page twice, because it gets the previously set cookie.
Apparently everyone suggest to use this practice, but its not working for me.
Am I missing something?
Cookies do not work that way. When a cookie is set, it is not available (i.e. a corresponding $_COOKIE key exists) until the next request.
What actually happens is:
client sends a requests
server sends a response containing a Set-Cookie response header field
After that the client sends the cookie along with any following request:
client sends a request containing a corresponding Cookie request header field
server registers $_COOKIE key
Per the docs:
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
If you need it accessible on the same page, use sessions instead, or do a redirect to the same URL after the setcookie call.
Cookies are set / received as part of http headers exchange, so, under usual circumstances are one of the first thing the client (browser) sends / receives. For your problem, the client only knows it's got a cookie to send on the second request.
Using a good Firefox extension like Live HTTP Headers can help you discover which stuff's sent when.