Check for first visit of a site - php

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.

Related

How do I catch cache for the user in CakePhp

I dont really have much experience in cache controlling and CakePhp. I am not a regular programmer as well. I got a situation where if the user is visiting a site for a first time there will be a pop up appearing on the screen. If the user visited it before there wont be any popup.
As for checking the user is authentic, i can use
<?php if (empty($auth_user)) { ?>
//codes for popup modal
<?php } ?>
My question is, is that possible to implement some logic like this to catch the cache or check wheather the tmp file is empty or not?
No there is not good ways to catch cache, But there only one way COOKIES to do it but it will be terminated and work newly as user just delete them in his browser.
As php is an server side scripting language
If you not want to save cookie then use LOCALSTORAGE but in JAVASCRIPT
1.COOKIE(Cookies can be stored via PHP)
setcookie(nameOfCookie, valueOfCookie, expireTimeOfCookie, pathOfCookie);
Simple insert "/" in pathOfCookie
Getting COOKIE in PHP
<?php
if(isset($_COOKIE[$nameOfCookie])) {
//User already visited your site.
} else {
//Use doesn't visited your site yet.
//Show POPUP here. And set cookie here (In Else Condition).
}
?>
Keep in mind that if the expiryTimeOfCookie passes it will expiry. And not exist (Time In Seconds For 1 Day = 86400

Avoiding people to refresh page?

i have some problem, i create a page to read news and if the page open it will be update in my database field for news_read +1 but i want if page refresh by user isn't +1
this is my query in page
$q="SELECT*FROM t_news WHERE news_id=$b_id";
$dataJ=mysql_query($q);
$a=mysql_fetch_array($dataJ);
$plus=$a['news_read']+1;
mysql_query("UPDATE t_news set news_read=$plus WHERE news_id=$a[news_id]");
anyone know, how to disable $plus=$a['berita_dibaca']+1; after refreshing the page?
UPDATE
UPDATE
thanks all ,i have solved my problem with session
i put
if ($_SESSION['load']==1){
$_SESSION['load']=0;
}
in all of my page except read.php and i put
if ($_SESSION['load']==0)
{
//QUERY
}
$_SESSION['load'] = 1;
in read.php
Method 1.
Save cookie, if user has cookie don't update database.
Method 2. (better)
Save users who have already viewed this article, and if user is in list do not update database.
Tip:
UPDATE t_news set news_read = news_read + 1 WHERE news_id = $a[news_id]
to avoid useless queries.
That's not a question to solve with sql, but with HTTP.
There is basically no difference between a refresh of a page and the inital request. There both just HTTP commands. There may be a difference in the headers of both requests but you can't always be sure they are present. So using the referer is probaly not a great idea.
Beside Valdas answer with the cookie you may also use the session of your user and set a flag there. (Although most session implementations do also use cookies, but in another way)
This method doesn't require a user to be logged in:
session_start(); // ignore if you're already using sessions
if( !isset($_SESSION['has_read_news'])) $_SESSION['has_read_news'] = array();
if( !isset($_SESSION['has_read_news'][$b_id])) {
mysql_query("UPDATE `t_news` SET `news_read`=`news_read`+1 WHERE `news_id`=".$b_id);
$_SESSION['has_read_news'][$b_id] = true;
}
Note that it's not completely foolproof (clearing the session cookie will allow the user to be counted again) but overall it should be plenty good enough.

Loading welcome animation only once jquery/php

In my site i have a welcome animation (created with jquery) which runs when any one opens my website (www.mysite.com). Then the same user going to anther page in my site for example www.mysite.com/about then click back to home (www.mysite.com) the animation again shows up. How can i restrict this ?
Share some logic like putting a session or settimeout or something like that.
This is how you could do it using jquery cookie plugin:
http://jsfiddle.net/lollero/2nYBV/ ( or http://jsfiddle.net/lollero/2nYBV/show/ )
You might want to change the way cookie expires. That info can be found in the plugin page. The way I did it, it expires after every browser session.
jQuery:
You could just as easily reverse this to hide, if the cookie is set. 1. Set cookie 2. if statement to trigger hide, if cookie is set.
// If "welcome" cookie is not set...
if ( $.cookie('welcome') === null ) {
// Show welcome text.
$('#welcome').show();
// Set the "welcome" cookie, so that the
// welcome text will not be shown after this.
$.cookie('welcome', true );
}
​
CSS:
#welcome {
display: none;
}​
HTML:
<div id="welcome">Welcome</div>​
See the following link for information on how to setup cookies using JQuery:
How do I set/unset cookie with jQuery?
Everytime you load the homepage, you can check if the cookie is set using an if-statement. If the cookie is not set, run the animation.
Within the animation-script; make sure that you set the cookie so that the script won't run again while the cookie is active.
You can set cookie either on server side or either client side
And check whether the cookie is set or not if cookie is set then dont show welcome box otherwise show the welcome box...
In php you can set session cookie using setcookie function please see below link:-
http://php.net/manual/en/function.setcookie.php
Place timer with flag then redirect to main page in your site.
setTimeout(function() {window.location.href = "/NewPage.php";}, 2000);
You can use a session to handle this.
An example:
<?php
$_SESSION['new'] = true;
?>
At first visit main page - define a flag in cookies, and at each visit of page check this flag

Detecting if cookies are enabled with PHP, header redirection

I am really suffering here trying to get this ajax call to work, sorry for the massiveness of this question.
The user clicks a button, this initiated an ajax call to add a vote to the database. Here is the file called "addvote.php":
<?php
session_start();
/* COOKIECHECK START */
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
header("Location:/thought/addvote.php?cookies=true&id=".$_GET['id']."&ans=".$_GET['ans']);
}
if(count($_COOKIE) > 0){
$cookies=1;
} else {
$cookies=0;
}
/* COOKIECHECK END */
if($cookies==1) {
$id=$_GET["id"];
$vId="v".$id;
if (((isset($_SESSION[$vId]) && ((time() - $_SESSION[$vId]) > 180))) || (!isset($_SESSION[$vId]))) {
// last vote was more than 3 minutes ago
$_SESSION[$vId] = time(); // update/create vote time stamp
//ADD VOTE TO DATABASE
}
else {
echo "You've voted on this already";
}
}
else {
echo "Please enable cookies to make your vote count";
}
?>
What is supposed to happen: The user is checked to see if they have cookies enabled. If so, they are allowed to add a vote, if not tell them to enable cookies. If they have cookies enabled, and they havn't voted already - add a vote, if they have voted already, tell them.
What actually happens: A user who hasn't voted yet clicks the button, this initiates the ajax call and the vote is successfully added, no message is sent to the user. They then move onto another question and click the vote button, "addvote.php" is initiated, but this time it returns "You've voted on this already" AND adds a vote! This makes me thing that the page call is running twice, first it adds the vote, then it tries again (and returns the error).
Maybe it has something to do with the header()??
Every question then returns this same message and adds a vote - unless I wait a while and then it works on the first question and the same thing happens again.
Point of note is:
The GET variables are passed along with the header so that I know which question they're talking about and whether they clicked no or yes.
Again, apologies, this question is a horrible one.
This will not prevent cheating with voting anyway. To test if user has cookies enabled, you can, for example, set cookie using JavaScript on voting page and check it in PHP. But, obviously, if someone wants to cheat, he or she will remove your cookies manually.
Furthemore, you need to add exit after header() call to make your code work:
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
header("Location:/thought/addvote.php?cookies=true&id=".$_GET['id']."&ans=".$_GET['ans']);
exit;
}

Destroy PHP session on page leaving

I need to destroy a session when user leave from a particular page. I use session_destroy() on the end of the page but its not feasible for me because my page has pagination. My page is: abc.php?page=1 or abc.php?page=2 or abc.php?page=3.
So, I need to destroy a session when a user leaves from abc.php page. How can I do it without using a cookie?
Doing something when the user navigates away from a page is the wrong approach because you don't know if the user will navigate to a whole different page (say contact.php for the sake of the argument) or he/she will just go to the next page of abc.php and, as Borealid pointed out, you can't do it without JS. Instead, you could simply add a check and see if the user comes from abc.php:
First, in your abc.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page:
$_SESSION['previous'] = basename($_SERVER['PHP_SELF']);
Then, add this on all pages, before any output to check if the user is coming from abc.php:
if (isset($_SESSION['previous'])) {
if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) {
session_destroy();
### or alternatively, you can use this for specific variables:
### unset($_SESSION['varname']);
}
}
This way you will destroy the session (or specific variables) only if the user is coming from abc.php and the current page is a different one.
I hope I was able to clearly explain this.
To trigger when the user actually leaves the page, you must use Javascript to send an asynchronous request back to the server. There's no way for the server to magically know the user has "left" a page.
See http://hideit.siteexperts.com/forums/viewConverse.asp?d_id=20684&Sort=0 .
I had a similar issue but mine was on a page reload I wanted variables that I had printed to be destroyed. It was for my login for my web design class I was making error feed back for if user put in a bad username or password. I could get the error to display but if I hit refresh page they errors would just stay there. I found that by just setting the variable to nothing after it printed would kill it. Take a look at what i did:
<p>To access my website please Login:</p>
<form name='login' action="./PHP_html/PHP/login.php" method='post'>
Username: <input type='text' name='username' /><div><?php print $_SESSION['baduser']; $_SESSION['baduser'] = "";?></div><br />
<div style="padding-left: 4px">Password: <input type='password' name='password' /><div><?php print $_SESSION['badpass']; $_SESSION['badpass'] = "";?></div></div>
<input type='submit' value='Login' /> or you can Register
I don't know if this helps at all but it worked for me.
Also, thanks to all you that post on sites like this to help those of us who are still learning.
For a particular page you need to destroy the session, then unset the all session variable
using
unset($_SESSION['varname']);
For the whole site you can use session_destroy();
I solve the problem.First take the current url then chk the page stay on current url.if page is not in the current url then destroy the session.
$url = "http" . ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$page_name="abc.php";
if (!preg_match("/$page_name/",$url))
{
session_destroy();
}
But this code should be used on another pages.Because http is a stateless processes so no way to find when a user leave the page.
You can't tell when a user navigates away from the page, it's simply not possible in any reliable manner.
The best you can do is exploit how cookies work. When starting a session, you're sending a cookie to the client which identifies the client on each subsequent visit, and hence activates the associated session. It is up to the client to send this identification on subsequent visits, and it's up to the client to "forget" his identification.
You can instruct the client to only send the cookie for certain pages, and you can instruct him to forget the cookie when closing the browser (with a lifetime of 0). This can be set using session_set_cookie_params.
Other than that, you can simply ignore the session parameters on pages where they don't matter. You can delete the session (or certain values of it) after some time of inactivity when you assume the client has left.
Borealid deserves credit for pointing to the most elegant solution.
A more kludgey solution is to keep an iframe on the page that is pointed to another "monitor" page which is set to refresh every few seconds. This can be done without JavaScript using:
<meta http-equiv="refresh" content="10">
This refreshes the monitor page every 10 seconds. When this happens, the monitor page can record the time (overwriting the previously recorded time) and session ID on the server somewhere (DB or file).
Then you would have to create a cronjob that checks the file/DB for any sessions that are more than 10~12 seconds old and delete them manually. The session data is usually stored in a directory (specified by your PHP config) in a file named sess_the-session-ID. You could use a PHP function like this:
function delete_session($sessId) {
$sessionPath = session_save_path();
// you'll want to change the directory separator if it's a windows server
$sessFile = "$sessionPath/sess_$sessId";
if (file_exists($sessFile) && unlink($sessFile)) return true;
return false;
}

Categories