So I'm currently making a site that includes purchases. Instead of signing up I want to set a cookie then every time a user clicks the buy button, it'll add 1 to the cookie name. Then when the cookie name = $_POST['user'] + 10 I want to echo 'too many right now' or something along those lines. I can't get this to work and have tried multiple times. There is no error in my html or anywhere else in my html. I just can't get this to work. Here is my code:
<?php
$cookie_name = $_POST['user'];
setcookie($cookie_name, time() + (86400 * 30), "/");
if(!isset($_COOKIE[$cookie_name])) {
print 'Cookie with name "' . $cookie_name . '" does not exist...';
} else {
print'Cookie with name "'. $cookie_name .'"value is:'.$_COOKIE[$cookie_name];
}
if(isset($_POST['button'])) {
setcookie($cookie_name, '+1', $cookie_value);
}
if (setcookie($cookie_name == $_POST['user'], +10)) {
echo 'to many right now';
}
?>
I obviously have a html form with the attributes name = 'button' and name = 'user' I just want to know how I can achieve what I said I was trying to do above. Any help is appreciated, thanks.
You are clearly out of your depth, and are hoping that somehow, setcookie will do all the work for you, reading, adjusting, and testing the cookie. As the manual makes clear it does only one thing:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers.
It takes two main parameters: a string which is the name of the cookie to send to the browser, and a string which is the value to send; the other arguments are all optional, and change when and where it will be visible; just ignore them for now. Note that the second argument is not an equation, or an adjustment to be made, it's just a string of text to store.
As ever, the key is to break your problem down; go through each of these steps, and make sure it's working before you go to the next step:
Decide on your cookie's name (the part that won't change, because it's how you'll find it again later).
Test if the cookie has already been set on a previous request.
If it has, put its value into a new variable.
Increment that value by 1
If there is no existing cookie, set the variable to an initial value, like 0 or 1
Send a cookie to the browser with the new value, using setcookie
Test if the value has reached some threshold, and echo a message.
Note that in the above, there is only one call to setcookie; most of your logic is just working with numbers, and doesn't need to know about cookies at all.
Related
I am willing to count unique visitors once landing on a specific page,
I wrote the below code, but the database updates each visit not uniquely,
tried to check the cookie in chrome settings, but did not find TestCookie
Then tried to check from Inspect->Network->Cookies I found my cookie in response cookies,
Actually, I don't know if this means that it was saved or not, because if it is saved, so why database updates each repeated visit...
<?php include "db.php"; ?>
<?php
if(!isset($_COOKIE['TestCookie'])){
setcookie("TestCookie","yes",60*60*24*320);
mysqli_query($dbConnection,"UPDATE visits SET otal_count = total_count+1");
print_r($_COOKIE);
}else{
return false;
}
?>
Can you try to change third (expires_or_options) paramater of setcookie to
time() + 60*60*24*320
setcookie("TestCookie","yes",time() + 60*60*24*320);
So I've scoured w3schools and this fine website for some time but I can't figure this out.
I have a script that creates a cookie in the users session upon loading the browser, and another script that will check the value of said cookie and respond with 2 echo's depending on the value.
Script to create the cookie is:
<?php
$cookie_name = "CTF";
$cookie_value = "ChangeThis";
if(!isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, $cookie_value, time() + 86400, "/", NULL);
}
?>
My IF check for the values is as follows:
<?php
if($_COOKIE[$cookie_value] = "CTF") {
echo "Congratulations. Your token code is 4HeWPzK63Lf5NkGS";
} else {
echo "Your cookie is not set yet.";
}
?>
The code works, and when the cookie is changed to CTF it echo's the correct line. However, when I then delete the cookie and refresh the page, essentially resetting the cookie back to the value of "ChangeThis", the first echo still appears on the page.
Can someone point me in the right direction?
The issue is your if condition. You have used = instead of ==. You are assigning the value instead of comparing. The condition checks if the assignment is successful or not. What you need is the below statement:
if($_COOKIE[$cookie_name] == "CTF")
Also, the cookie value is not "CTF", that's the cookie name, you should compare with the value you are setting it to.
<!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.
I have a cookie set like this:
$_COOKIE['admin'] = 'foo';
Now the first time, I can see this cookie getting serialized using var_dump($_COOKIE['admin']) So, I removed that cookie and just placed this instead.
if(isset($_COOKIE['admin']){
echo 'hello admin';
}else{
echo 'hello visitor';
}
Normally this should work for all pages, but it only works once. Meaning, if I browse index page, it works, if I navigate to other page (same website) then comeback to the index page, the cookie gets lost. And there is nothing to destroy/unset any cookie/session in any page.
What could be the problem here
I think you're supposed to set cookie values like this:
setcookie("name","value", $time, "/");
This is covered here in the PHP docs.
To make cookie work in all pages, use like this
$value = 'foo';
setcookie('admin', $value, time() + (60 * 60 * 24));
Now, a cookie named 'admin' with value 'foo' will be available for 1 day. The path parameter is optional. But if you set it to "/", it will be availabel within entire domain.
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