PHP Count Unique Visitors ,, Not Works - php

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);

Related

Set cookie and redirect if cookie set based on url

I am running woocommerce/wordpress and noticed customers refreshing the thankyou page cause google analytics to record multiple transactions.
The url they visit is: /checkout/order-received/24420/?key=wc_order_a5m1jzQDJLjjr
I figure i need to Set a cookie using that order number. If cookie exists then redirect before analytics code runs. Thus preventing reloads of thank you page.. (i hope)
I don't know who to extract the number 24420 from the url and set a cookie. Redirecting on Cookie i can figure out.
thanks
/J
To retrieve the Order ID
$order_id = wc_get_order_id_by_order_key( $_GET['key'] );
I would suggest to use a session instead of cookie so you can do something like
if(isset($_SESSION['order_'.$order_id])) {
header("Location: /where-you-want");
die;
} else {
$_SESSION['order_'.$order_id] = 1;
}
Please note that both Session and Cookies need to be set before any other output on the page, so be sure that the code you're running is executed before any HTML is printed.

I can't delete cookies PHP although path and time was set correctly

I have created a logout.php page to let the user sign out from the website and redirects them to the sign in page.
however what ever i do, the cookies are not getting deleted, so when the user gets redirected to the singin page the latter examines the cookies and then find it, therefore logs the user in.
Below is the code of logout.php:
<?php
unset($login);
if (isset($_COOKIE['xxx'])){
setcookie('xxx', false, time() - 3600,"/");
}
if (isset($_COOKIE['yyy'])){
setcookie('yyy', false, time() - 3600,"/");
}
header("Location: singin.php");
die();
?>
Please note that this php page is in subfolder protected by password and the html link redirects to a php file that require() the logout.php file.
use php unset() to delete your cookie as, you can get the complete details here delete the cookie
if (isset($_COOKIE['xxx'])){
unset($_COOKIE['xxx']);
}
if (isset($_COOKIE['yyy'])){
unset($_COOKIE['yyy']);
}
or, set value as null and a negative time for your cookie as
setcookie('xxx', null, -1, '/');
setcookie('yyy', null, -1, '/');
or, set value as empty and a past time for your cookie as
setcookie("xxx", "", time()-3600);
setcookie("yyy", "", time()-3600);
I have found finally the reason behind the issue.
it's because I have put session_cache_limiter('public'); in my code, so which I presume prevents the client to set the cookie to an expiry date.
I have done that because I don't want the client to ask the user each time they hit back to resubmit the form.
It seems that it's not the correct practice, I'll post another question for that.
Thanks all for the help.

Session not working for first time, from second time it works

I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.
First Page
<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];
$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);
if($data1>0)
{
$_SESSION['user_id']=$val['user_id'];
echo "<script>window.location.href='index.php'</script>";
}
else
{
echo "<script>window.location.href='login.php'</script>";
}
?>
Second Page
<?php
session_start();
$val=$_SESSION['user_id'];
echo $val;
?>
session_start(); should be at the very top of both scripts!
Session variables are saved on server and assigned a unique code that are passed to browser in cookies.
Because the cookies are set by the headers they need to be sent before anything else!
Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.
So always start the both scripts like this:
<?php
session_start();
// Rest of the code....
It looks like they are on top on your question but I think you edited question later to put there.
That's the only reason sessions are not working the first time and they are working on second time.
instead of the echo use
header("Location: index.php");
EDIT
alsosession_start should be declared at the top of the first page because you cant set a session that doesn't exist in the context if you were running it in a console environment you would receive the following error
"$_SESSION['user_id'] does not exist in the current context"
same happening here. is php 5.6 is super strange problem. on some pages work normaly and on one dont. First request is like dont get recognized.. :)
for example: set
#when page load set:
$_SESSION['a']=0;
#then with JS requests increase $_SESSION['a']+=1; and this start working on third request...

Include both the page counter and the last accessed time of the web page in one cookie.

How to include both the page counter and the last accessed time of the web page in one cookie? So that each time When I retrieve cookie information, it gives me both the details.
<?php
$inTwoMonths=60*60*24*60+time();
setcookie('lastVisit',date("G:i - m/d/y"),$inTwoMonths);
if(isset($_COOKIE['lastVisit']))
{
$visit=$_COOKIE['lastVisit'];
echo "Your last visit was - ".$visit;
}
else
echo "You've got some stale cookies!";
?>
Your example is never gonna work. When setting the cookie, the actual value is not available for PHP. PHP sends the cookie to the browser along with the rest of the headers and only the next time you load the page, the cookie is send from the browser to the server and has a value retrievable for PHP.
But to answer your question:
A cookie can store an array. See example 3 of the manual.
You could do something like:
$page_counter = 371;
$last_visit = date("G:i - m/d/y");
setcookie('lastVisit[count]',$page_counter,$inTwoMonths);
setcookie('lastVisit[visit]',$last_visit,$inTwoMonths);
On the next load, you can then do
$cookie_value=$_COOKIE['lastVisit'];
echo $cookie_value['count'];
echo $cookie_value['visit'];

Check for first visit of a site

Guys how can I check when the users first visited the website? because I want to display a pop up message when he/she first visited the website.,I found this question and this website http://www.electrictoolbox.com/jquery-cookies/ but I don't know how to use it. I just wrote a simple code in order for me to check how it is done.
<script type="text/javascript">
$.cookie("example", "foo");
alert( $.cookie("example") );
</script>
but its not working. What I am doing wrong here? or maybe you can suggest for another method. Any help would be much appreciated. Thanks.
You first need to check whether the cookie exists, and if so do the message (please don't use alert for that), and then set the cookie. E.g.:
if (!$.cookie("yourcookie")) {
// Show a message (please don't use alert)
}
$.cookie("yourcookie", "anything not blank here");
Of course, this only checks that the user doesn't have the cookie, it doesn't necessarily mean they've never been to the site before (as users can clear cookies).
download the js from this URL https://github.com/carhartl/jquery-cookie and import into your code
you can set cookie $.cookie("example", "foo"); OR ($.cookie("example", "foo", { expires: 7 }); - cookie last for 7 days
)
you can retrive the cookie by $.cookie("example");
using these
if(!$.cookie("example"))
{
alert('not 1st time');
}
{
alert('1st time');
$.cookie("example", "foo"); //set the cookie
}
On index page check if some cookie exist, if not set cookie to indefinite time and next time user returns to page you will know that he already visited (if he didn't remove cookies from browser). You could also put his IP address with some other data in your DB and check from DB if user has visited before, but it is also unreliable because there are ways you can change your IP also, depends on what are you trying to achieve and how important it is to know if user has visited page before.

Categories