How do I catch cache for the user in CakePhp - php

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

Related

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.

Force user to logout session PHP

I can't seem to find a straightforward answer to this question. Is there a way in which I can force a logged in user to logout? My login system essentially just relies on a session containing the user's unique ID (which is stored in a mysql database). So essentially just...
if (isset($_SESSION['user_id'])) {
echo "You're logged in!";
} else {
echo "You need to login!";
}
But let's say I want to ban this user, well I can change their status to banned in my database but this won't do anything until the user logs out and attempts to log back in... So, how do I force this user to logout? Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server. Any help is appreciated, thank you.
Either you need to check every time they load a page, or possibly look at an Ajax call at set intervals to check their status from the DB.
Then you can use session_destroy(); to end their session. This will destroy their entire session.
Otherwise you can use unset($_SESSION['user_id']); to unset a single session variable
Preferably without checking every single time they view a page whether or not their status has been switched to "banned" because that seems like unnecessary stress on my server.
Loading the user from the database on every page load, rather than storing a copy of the user in the session, is a perfectly reasonable solution. It also prevents the user from getting out of sync with the copy in the database (so that, for instance, you can change a user's properties or permissions without them having to log out and back in).
Try to put this on every page...
if (isset($_SESSION['user_id'])) {
$sql = "SELECT from tbl where status='banned' and user_id=$_SESSION['user_id'] ";
$query = mysql_query($sql);
if(!empty(mysql_num_rows($query))){ // found the banned user
//redirect to logout or
//session_destroy();
}
} else {
echo "You need to login!";
}
if the user is still logged in... check if his/her status is banned or not... if banned.. then logout
You can unset it.
unset($_SESSION['user_id'])
You could use Custom Session Handlers this way you have full control where and how the session data is stored on the server.
So you could store the session data for a particular user in a file called <user_id>.session for example. Then, to logout the user, just delete that file.
Ajax calls in an interval will put extra load on server. If you want real-time response to your actions(e.g. the user will be signed out right when you ban them from your system backend), then you should look into something like Server Push.
The idea is to keep a tunnel open from Server to Browser whenever a user is browsing your website, so that you can communicate with them from server-side too. If you want them to be banned, push a logout request and the process that in your page(i.e. force logout by unsetting session).
This worked for me am using pHP 5.4
include 'connect.php';
session_start();
if(session_destroy())
{
header("Location: login.php");
}
You can use session_save_path() to find the path where PHP saves the session files, and then delete them using unlink().
Once you delete the session file stored in the sever, the client side PHPSESSID cookie will no longer be valid for authentication and the user will be automatically be logger out of your application.
Please be very careful while using this approach, if the path in question turns out to be the global /tmp directory! There's bound to be other processes other than PHP storing temporary data there. If PHP has its own directory set aside for session data it should be fairly safe though.
There is a few ways to do this the best in my opinion based on security is:
NOTE: THIS IS REALLY ROUGH.... I know the syntax is wrong, its just for you to get an idea.
$con = mysql_connect("localhost","sampleuser","samplepass");
if (!$con)
{
$error = "Could not connect to server";
}
mysql_select_db("sampledb", $con);
$result = mysql_query("SELECT * FROM `sampletable` WHERE `username`='".$_SESSION['user_id']."'");
$userdeets = mysql_fetch_array($result);
if($_SESSION['sessionvalue'] != $userdeets['sessionvalue'])
{
session_destroy();
Header('Location: logout.php');
}
else
{
$result2 = mysql_query("UPDATE `sessionvalue` WHERE `username`='".$_SESSION['user_id']."' SET `sessionvalue` = RANDOMVALUE''");
$sesval = mysql_fetch_array($result2);
$_SESSION['sessionvalue'] = $seshval
}
Now I know thats not the very code but in essence what you need to do to be secure and have this ability is:
Everytime a page load check a Session value matches a value in the DB.
Every time a page loads set a new session value based on a random generated DB value. you will need to store the username in a session as well.
if the Session ID's do not match then you destroy the session and redirect them.
if it does match you make the new session ID.
if you want to ban a user you can set their sessionvalue in the DB to a value like "BANNED". this value will not allow them to log in either. this way you can control user through a simple web form and you can also generate list of banned users very easily etc etc. I wish I had more time to explain it I hope this helps.

PHP session issues

I have a mobile script from detectmobilebrowsers.com that will redirect the user to my mobile site however I also wish that when the URL "http://example.com/?mobile=no" is entered a session will be created that won't redirect the user on every page of my site...
$mobile=$_GET['mobile'];
if(isset($_SESSION['mobile'])){
if($_SESSION['mobile']==="no"){
complete();
}
else{
$_SESSION['mobile']="no";
complete();
}
}
elseif($mobile==="no"){
$_SESSION['mobile']="no";
complete();
}
elseif($_SESSION['mobile']!="no"){
checkMobile();
}
function checkMobile(){
// Mobile Detection Code taken out to save space.
gotoMobile();
}
function gotoMobile(){
echo "<script>window.location='http://m.MySite.org/';</script>";
}
function complete(){
return false;
}
Sorry if I seem confusing but in short terms: Mobile Detection (which is set)... make session mobile=no if user does wishes to view full site and when that session is created it is checked on everypage (same php script) and if I set my session for no mobile I want that to stay on everypage... In my case the only thing that happens is the first page is not redirected but when I go to another page it won't display it unless I add the ?mobile=no but the whole point of the sessions here is so this only needs to be done once.
Before you can begin storing user information in your PHP session, you must first start the session:
session_start();
There must be no markup ouputted before session_start(), not even whitespace! (unless output buffering is used).
See http://php.net/manual/en/function.session-start.php.
It sounds simple, but are you sure you are using session_start() at the top of every page before checking all of your session variables?

CakePHP delete session on user leave

How could I check if a user has left my login form? Not logging in but actually leaving it?
As I want to delete the Auth.redirect session if they choose not to login so that when they return later they are not taken to their previous session!
So essentially running this:
$this->Session->delete('Auth.redirect');
I'm thinking some kind of check in the AppController that knows when a user was referred from the login form and deletes the session auth.redirect???
Or better yet checking if the current page is the login form and if not then delete the session!!!
and for those that are interested, this is how my login method currently looks:
function login()
{
if(!(empty($this->data)) && $this->Auth->user())
{
$back_to = $this->Session->read('back_to');
$auth_redirect = $this->Session->read('Auth.redirect');
if($auth_redirect)
{
$this->redirect($auth_redirect, null, true);
}
else if($back_to)
{
$this->redirect($back_to, null, true);
}
else
{
$this->redirect($this->Auth->redirect(), null, true);
}
}
else
{
$this->Session->write('back_to', $this->referer());
}
}
Thanks
I am not familiar with CakePHP but your question sounds a bit strange to me. You are talking about PHP, a server side scripting language. A PHP script gets executed only when a request comes in (please correct me if there is something I don't know yet).
So, when a user calls the login page, the script gets executed. Now think of the following: Just after the login page has been loaded, the user closes the browser-tab with the login page. This does not trigger a request, so there is no possibility to inform the server about that action.
Maybe CakePHP can do such magical things, but I think we are talking about stateless HTTP, so I can't imagine how to realize something like that.
You could add a timestamp to the session of when you have last received a request from the user. For example, in AppController::beforeFilter, just add $this->Session->write('lastSeen', time()). You can then check how much time elapsed between the last time the user opened any page, and discard the Auth.redirect value if that interval was too long.
That's basically the same as expiring the session, just in a more controlled fashion. If you want to count the time a user simply has your page displayed on his screen as "activity" as well, you can use some Javascript AJAX to keep sending requests to the server to signal "I'm active!"
That's all quite a lot of work for very little benefit though. HTTP is stateless and doesn't allow you to track the user easily, period. Actually tracking whether a user is "actively" watching your page or not incurs a huge overhead and in this case seems like misplaced effort for the extraordinarily narrow purpose you want to use it for.
if($this->here != '/admin/login')
{
$this->Session->delete('Auth.redirect');
}
or this:
if($this->here != Router::url(array('admin'=>true,'controller'=>'users','action'=>'login')))
{
$this->Session->delete('Auth.redirect');
}

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