Using Cookies to check if someone has visited a page - php

When a user visits one page I have:
setcookie("firstvisit", time()+3600);
In a functions file which is included in the header of every page I have:
if(isset($_COOKIE['firstvisit'])) {
$run = mysql_query("UPDATE `table` SET `firstvisit` = 1 WHERE `id` = '".$_SESSION['uid']."'");
setcookie("firstvisit", time()-3600);
If I do it like this (and it works) it means the script will run every time the user clicks on that page. Is there any other way to accomplish this?

Your code will only set firstvisit to 1 in the database on the second visit. This is because isset($_COOKIE['firstvisit']) must evaluate to true for the query to run, and cookies are only available in the next request - setcookie() doesn't add to the $_COOKIE array.
// assumes $_SESSION['uid'] is always set
if(!isset($_COOKIE['firstvisit'])) {
setcookie('firstvisit', time()); //set a cookie containing the timestamp of when this user first visited the page
$run = mysql_query("UPDATE `table` SET `firstvisit` = 1 WHERE `id` = '".$_SESSION['uid']."'");
}
else {
//it's not their first visit because the cookie already exists
}
Be aware that this logic won't work on multiple pages - the cookies will overwrite each other and the code will become unreliable.

You can check to see if the cookie is previously set or not before setting it.
if( !isset($_COOKIE['firstvisit']) ){ //if the cookie is not set
//set your cookie
} //skip otherwise

If you don't want to update the value every time. check that value in database whether it's already exist or not?

Related

PHP page keeps refreshing after COOKIE is set

The following code is the first code in my php page.
$current_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(isset($_REQUEST["lang"])){ //check if different language was selected
$lang = $_REQUEST["lang"];
if($lang == "eng"){
$lang_value = 1;
}else{
$lang_value = 0;
}
setCookie('language',$lang);
setCookie('language_value',$lang_value);
header("Refresh:0; url=".$current_link);
}else{ //if different language was not selected, check if cookie is set with language value
if(isset($_COOKIE["language"])){
$lang = $_COOKIE["language"];
$lang_value = $_COOKIE["language_value"];
}else{ //if cookie with language value is not set, create it now with default language option
setCookie('language','eng');
setCookie('language_value',1);
header("Refresh:0; url=".$current_link);
}
}
The visitor can only choose one of two languages. If a language is chosen, cookies with the chosen language values are created.
If a language is not chosen, the script checks if a cookie with the language value exists, and if so, accesses the cookie values. If a cookie with the language value does not exist, cookies with the default language (English) values are created.
The page is suppose to only refresh when cookies are created and continue the rest of the code if the cookie with the language value exists. However, the page keeps on refreshing even after the cookies were created and are accessible. eg:
echo $_COOKIE["language"]; //will output the selected language value
Not sure if there is something wrong with the logic here, but any help will be appreciated.
Thanks
I managed to solve the mystery.
The problem was in the .htaccess file setup, eg:
RewriteRule diploma-golf course.php?lang=eng&courseid=15 [NC])
Since I only saw the 'diploma-golf' part at the end of the url, I never realised that the "lang" value was passed on every time the page refreshed. So because the script received the "lang" value each time, it created a new cookie each time, resulting in the infinite refreshing. Changed the if statement logic and now everything is working as it should.
Every request to the page will run this part:
if(isset($_REQUEST["lang"])){
That means that the page will be refreshed because of this unconditional part of your code:
header("Refresh:0; url=".$current_link);
What you might want to do is removing the first Header part and only keep the header part as described in your text.
It would look like so:
$current_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(isset($_REQUEST["lang"])){ //check if different language was selected
$lang = $_REQUEST["lang"];
if($lang == "eng"){
$lang_value = 1;
}else{
$lang_value = 0;
}
setCookie('language',$lang);
setCookie('language_value',$lang_value);
#header("Refresh:0; url=".$current_link); ### Removing this line
}else{ //if different language was not selected, check if cookie is set with language value
if(isset($_COOKIE["language"])){
$lang = $_COOKIE["language"];
$lang_value = $_COOKIE["language_value"];
}else{ //if cookie with language value is not set, create it now with default language option
setCookie('language','eng');
setCookie('language_value',1);
header("Refresh:0; url=".$current_link);
}
}
You need to add expire and path for the cookie:
setCookie('language',$lang, time() + (86400 * 30), "/"); // 86400 = 1 day

Destroy the Session from a other user

I try to destroy the Session from a other user after I changed his permissions or his ban-status...
I write the session key from every user in to the database and catch them if I visits there Profiles. If there are any changes I want that the User will get kicked out of the System instantly...
Here is my code:
FUNCTION back_to_home() {
mysqli_close($db);
$session_id_to_destroy = $_SESSION['visit_user-session_id'];
session_id($session_id_to_destroy);
session_start();
session_destroy();
unset($_SESSION['visit_user-username']);
unset($_SESSION['visit_user-e_mail']);
unset($_SESSION['visit_user-register_date']);
unset($_SESSION['visit_user-last_login_date']);
unset($_SESSION['visit_user-register_ip']);
unset($_SESSION['visit_user-last_login_ip']);
unset($_SESSION['visit_user-steam_id']);
unset($_SESSION['visit_user-permissions']);
header('Location: ../../../');
exit;
}
I hoped I can fix or do that with PHP. I have no clue of JavaScript xD
So what I want to know is, Can I do that like that or is there another way to kick out another user from his session?
I try to destroy the Session from a other user
You can technically do this, yes, but the process is long winded and problematic.
How to delete an arbitary session.
A: Finding the session
You need to use the session_id value. This value is part of the file name (or in the case of database sessions the session identifier column value).
You need to know the file name precursor (usually sess_ but can be anything as set in the PHP source code). You also need to know the session storage location as set in your PHP.ini file.
Example:
A session with id 58ce93c623376b3ddfca3cfc3a01d57d3be85084363147464 is a file at:
/home/session_storage_folder/sess_58ce93c623376b3ddfca3fc3a01d57d3be85084363147464
But session file names are generated on the fly and are not (and should not be) connected to whose who on your membership database.
If you generate session id's manually then this becomes easier, but the security of sessions becomes greatly reduced and this should really, really not be done without very careful thought.
B: Finding the user
Now you need to find the User that you want to ban. The session file will contain the users id, somehow,
Session data is stored typically as:
(Example)
$_SESSION['alpha'] = "UiOvMfV9byatH4Wt1SPYUO3zgsj5";
$_SESSION['beta'] = 1324;
alpha|s:28:"UiOvMfV9byatH4Wt1SPYUO3zgsj5";beta|i:1324;
Which is
[var name]|[var type]:[var contents length]:[contents data]; [etc....]
So if you had a user id value set as $_SESSION['user_id'] = 45; this would be:
user_id|i:45;
In the session. So you would need to search every session you had for this data string.
Please read this question about how to do this
So you would have code like this:
$string = 'user_id|i:".(int)$user_id_to_block;
$session_file_name = null;
foreach (glob('/home/session_folder/*') as $file) {
$content = file_get_contents("/home/session_folder/".$file);
if (strpos($content, $string) !== false) {
$session_file_name = "/home/session_folder/".$file;
}
}
Once found, you can then delete that session on the server.
if(file_exist($session_file_name)){
unlink($session_file_name);
}
BUT:
With many sessions this will be very slow and inefficient.
How you Should be doing it
Each page load you should be checking the logged in user is authenticated. Assuming your user details are database driven, every page load you should be checking that the details are genuine.
<?php
session_start();
if($_SESSON['user_id'] > 0){
/////
$sql = "SELECT banned FROM users WHERE user_id = :user_id";
/////
// Etc. etc.
$result = get MySQL result;
if($result['banned'] === 'Y'){
/***
* Member is banned. kick them out.
***/
$_SESSION = []; // reset session.
header("Location: index.php");
die();
}
}
UPDATE
If you are using the session ID as an identifier and you know the session id without needing to search for it; simply do this:
FUNCTION back_to_home() {
mysqli_close($db);
// save current admin session (optional).
$admin_session = session_id();
// get target id.
$session_id_to_destroy = $_SESSION['visit_user-session_id'];
// close the current session.
session_write_close();
// load the specified target session
session_id($session_id_to_destroy);
// start the target session.
session_start();
// clean all session data in target session.
$_SESSION = [];
// save and close that session.
session_write_close();
// Optional if you need to resume admin session:
// reload admin session id
session_id($admin_session);
// restart admin session. . ..
session_start();
// ...
// header should go to a specific file.
header('Location: ../index.php');
exit;
}

Why PHP Cookie variable is not saved after closing Chrome

i'm learning to use cookies in PHP. I was expecting that every time i set a cookie, the cookie and all of his variables are stored on the client site so i could use them again next time the user will visit the site. Anyway in the next example (a web application with a sign in option, i use cookies to store a unique string so i could implement "Remember me" option) i can access the id of the stored cookie but the variables data seem lost. Here is example of the code i use and screenshots of what i get.
Setting up a Cookie
if (isset($_POST['remember_me'])) {
$token=uniqid($_SESSION['id']);
$sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
$conn->query($sql);
setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
else{
setcookie("remember_me","",time()-1000);
}
User page
On the user page it just simply prints out the $_COOKIE and $_SESSION array.
<?php
echo "SESSION: ";
print_r($_SESSION);
?>
<br>
<?php
echo "COOKIE: ";
print_r($_COOKIE);
?>
Process:
First i delete all the cookies using the advice i found here:
how to delete all cookies of my website in php
Then log inside Log in screen (this form call a script that execute the code for setting a cookie i gave at the beginning, then redirect to the user-page) User page before closing
Close the browser and open it again directly at the user-page (without executing other scripts /localhost/MIAFormApp/script/db/HTML_PROBA/user-page.html.php User page after re-opening
What did i get wrong and why the cookies array after re-opening is empty?
EDIT:
The second time i open browser the script for seting the cookie is not executed. I just set the url to go to the user-page.php .
Examp:
/localhost/MIAFormApp/script/db/HTML_PROBA/user-page.html.php
Try deleting the else statement in your sample code - meaning go from:
This
if (isset($_POST['remember_me'])) {
$token=uniqid($_SESSION['id']);
$sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
$conn->query($sql);
setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
else{
setcookie("remember_me","",time()-1000);
}
To this
if (isset($_POST['remember_me'])) {
$token=uniqid($_SESSION['id']);
$sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
$conn->query($sql);
setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
When you re-open your browser, the if statement is going to check whether or not the POST variable remember_me was found. The only time that it will be found is when someone logs in because the login form is sending that information on form submit. In every other instance ( such as re-opening the browser), the else statement will be executed which isn't what you want. The reason being that setting an empty value on a cookie will delete said cookie.

avoid page counting when click refresh button

I made a php script to counts the number of users have viewed my website's pages. This is my code
<?php
require_once ('test.php');
$institute_id = 14;
$q = "INSERT INTO page_views2 ( institute_id, views) VALUES ( $institute_id, 1)
ON DUPLICATE KEY UPDATE views=views+1"
;
$r = mysqli_query ($dbc, $q);
?>
I added this to top of my webpages and this is working (views incrementing) properly when I open the pages. But my problem is When I refresh the page, page views is incrementing by 1. It is okey when it is open first time. But I want to avoid from this when someone is refreshing the page.
so can any body tell me how can I do this?
Use sessions?
require_once ('test.php');
$institute_id = 14;
//if no such session exists, assume that its their first time viewing.
if(!isset($_SESSION[$institute_id.'_v'])){
//insert
$q = "INSERT INTO page_views2 ( institute_id, views) VALUES ( $institute_id, 1)
ON DUPLICATE KEY UPDATE views=views+1"
;
$r = mysqli_query ($dbc, $q);
//set session variable saying they've viewed this institutions page.
$_SESSION[$institute_id.'_v'] = 1;
}
Refreshing a page results in a new page request, so it obviously triggers your script on the server side. There's no way to alter this behaviour. What you can do is to implement some kind of checking, if the user requested the same page again (refresh) or not. You can store some info in your session/cookies and then just compare the values.
You could use cookies or sessions for that, I guess. Make a session variable that holds a timestamp of the latest visit. If the same page gets loaded again within an hour or so, the counter does not increase.
You can try to use 2 variables, one to define the name of each page you are visiting and one $_SESSION variable. You can set the $_SESSION with the name of the page you are viewing after you increment a counter with the query. Make the control variable each time before making the increment query and if the session variable has the same name as the page you are viewing skip the increment operation. Hope that helps.

Set cookie and update cookie problem - Php

In an attempt to get more familiar with cookies I've decided to set up a simple cookie management system to have more control of the information that I can store and retrieve from a user.
The idea is to set a cookie if it does not exist, and update a cookie if it already exists on the user.
Once the cookie is set, it will also be stored in a database that will keep track on when the session started and when it was last accessed.
Creating a cookie worked well at first. But suddenly it stopped working and wouldn't set anything at all. This is the current code of the createSession() function:
function createSession() {
// check to see if cookie exists
if(isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test","$cookiekey",$expire,"/",false,0);
} else {
// assign unique cookie id
list($msec,$sec)=explode(" ",microtime());
$cookiekey = preg_replace("/./","",($msec+$sec));
// set time
$expire = time()+81400;
// set cookie
setcookie("test","$cookiekey",$expire,"/",false,0);
// assign the unqiue id to $_COOKIE[]
$_COOKIE["test"]=$cookiekey;
unset($cookiekey);unset($msec);unset($sec);unset($expire);
}
}
Is my approach heading in the right direction or have I done something way wrong?
Doing $_COOKIE["test"] = something; doesn't make a "test" cookie. You need to use setcookie again.
I don't know why you'd want to do that though. Why not just check for $_COOKIE["name"] (the cookie that you are making).
Cookies are only available once another request was done. So don’t modify $_COOKIE on your own.
Furthermore, when in your case the cookie exists (i.e. $_COOKIE['test'] is set) you call setcookie again with $cookiekey as its value. But $cookiekey is not defined at that moment so the cookie will be overwritten with an empty string. I guess you want to use $_COOKIE['test'] instead:
if (isset($_COOKIE["test"])) {
// update time
$expire = time()+81400;
setcookie("test", $_COOKIE["test"], $expire, "/", false, 0);
}
You could also save yourself all that pain by using PHP's built in session management (examples here) to handle all of this cookie stuff for you.

Categories