Destroy session in PHP - php

Hi guys I am working on a program which will execute the number of people visit a website and when the date changes it will start from 0. So I have nearly figure out how to do it but it doesn't appear as 0 when the date changes here is my code:
<?php
session_start();
?>
<?php
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "You are the ". $_SESSION['views'] ." Visitor";
?>

As #Zwirbelbart said, don't use sessions for solving this. Use a DB, or at least a file, where you'll store the number of visitors.
Something like this:
function incrementVisitorsCount() {
$currentDay=date("Ymd");
if(!isset$_SESSION["visited"] || $_SESSION["visited"] != $currentDay) {
incrementYourDailyCounter($currentDay);
$_SESSION["visited"]=$currentDay;
}
}
incrementYourDailyCounter being the function that will increment the relevant value in the storage you chose (I would suggest a table in a DB you're most certainly already using).
You can base your counter on IP instead of sessions, but it means that you keep a record of each IP that visited your website each day.

Related

Sending value from one page to another with php session [duplicate]

This question already has answers here:
how to pass value from one php page to another using session
(2 answers)
Closed 6 years ago.
Im using wordpress
I wanted to send the data that is collected by form in the first page to the next page I didn't find anything that can send array data to another page other than GET command, GET commands uses URL, The reason I'm not using this GET is the sending information includes price values that are calculated using entered information
I found this $_session seems ok to my case (If any others are available, please tell me), Used wp session manager plugin to use $_SESSION.
im using it like this,
if(!isset($_SESSION)){
session_start();}
if(isset($_GET['B2'])) {
$_SESSION["info"] = "user-form";
$_SESSION["weight"] = $weight;
$_SESSION["price"] = $weight;
buy_now(); }
The B2 is a buy now button
function buy_now(){
if(isset($_GET['B2'])) {
header("Location:".get_site_url()."/buy-now/");
}
if(!isset($_SESSION)){
session_start();}
echo $_SESSION["info"]."<br>";
echo $_SESSION["weight"]."<br>";
echo $_SESSION["price"]."<br>";
}
The weight and price are Undefined index, the info will display.
What is the problem here? and How can I send variables to another page?, I'm unable to find any solution for now. Please help with this... Thank you
whenever you are need to check the session is start of not you should not check ist with $_SESSION you need to check the session_id() is generated or not (check the post for check the session start Check if PHP session has already started)
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_GET['B2'])) {
$_SESSION["info"] = "user-form";
$_SESSION["weight"] = $weight;
$_SESSION["price"] = $weight;
buy_now();
}
word press provide another method like
wp_cache_get /
wp_cache_set
which you can use as own CMS method for passing data from one page to another page by define expiry time as well.
wp_cache_set
wp_cache_get
I think you have to try POST method.
<form action="test.php" method="post">
<input type="text" name="my_value" value="value"/>
...
</form>
On next page
<?php echo $_POST['my_value'];?>
That's it.
Refer https://codex.wordpress.org/Class_Reference/WP_Object_Cache for detailed explanation and remember to delete / reset as per your use case else might be a problem.

How to prevent users to open same page more than once at a time

On my website people earn points by seeing a page. They get 1 point for each second they keep the page open (the page keeps rotating Advertisements).
Some people have started exploiting this by opening that page multiple times all together and hence are earning more points! for example if the user open the page 10 times then he is earning 10 points for each second. I don't want them to earn more than 1 point per second.
How can I prevent the users from opening that page more than once at the same time?
Thanks in advance.
note : My website is php based.
I have on easy but not reliable way in mind:
Set a Sessionvar like
$_SESSION['user_already_on_page'] = true;
Now you can check for this variable and return an error page or something like that.
if($_SESSION['user_already_on_page'])
{
//maybe the user has left unexpected. to workaround this we have to check
//for the last db entry. Examplecode:
$query = mysql_query($_db,'SELECT LastUpdated FROM Pointstable WHERE U_Id = $uid');
$row = mysql_fetch_array($query);
if((time()-$row['LastUpdated']) < 5)
{
die("You are already on this page!");
}
//$_SESSION['user_already_on_page'] is set but the last update is older than 5 sec
//it seems, that he unexpectedly lost connection or something like that.
}
To unset this variable you could fire an AJAX-Script on pageclose that unsets this variable.
So your unsetonpage.ajax.php could look like this:
<?php $_SESSION['user_already_on_page'] = false;?>
And your JS-Part (using jquery):
$(window).bind('beforeunload', function(eventObject) {
$.ajax({url:'./ajax/unsetonpage.ajax.php',type:'GET'});
});
This should work.
Add the time when the page is opened to the database. Whenever the page is opened check if the difference b/w that time and current time is less than xx seconds then redirect the user. If the difference is more than xx seconds then update that time.
//--- You make session in startup called (my_form)
if (!empty($_SESSION['my_form']))
{
if ($_SESSION['my_form']== basename($_SERVER['PHP_SELF']))
{
header("Location:index.php");
exit();
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}

Display data if usertype is admin otherwise display error message

I currently have a list of users in my mysql database. One of the columns is "type". I am trying to display certain data if type is equal to admin. If type is equal to anything else, it should just echo an error message.
Unfortunately, I have tried multiple methods but it just does not seem to be working out for me. Can anyone help me get this to work properly?
This is what I have, but obviously I am doing something wrong....
<?php
$usertype = $_SESSION['type'];
if ($usertype == "admin" ){
?>
admin stuff only goes here
<?
}
else
{
echo "not priveleged usertype";
}
?>
EDIT:
The following code works when displaying via username, however, I need content displayed by usertype, not the username.
<?php
if($_SESSION['user']['username'] == "oneoftheadminusernames" )
{
?>
Each page has to start with
<?php
#session_start();
?>
otherwise, php does not "see" the sessions contents. So that's probably it.
The # prevents the php error: A session has already been started... by the way.
Now, every page that uses the session must have this directive at the top.
At least, in a quick example, that reproduces your error perfectly.
If you are saving each logged in users type field in $_SESSION['type'] variable than the code you are writing is correct. Or if you are storing type in another variable than you that variable to check.
i have an idea like add a field EnableFlag in the table. if enablee flag is set to 1 consider it as a admin else as a User;

If statement, sessions variables

The following code is within an ajax call. I'm trying to make sure people don't vote on questions with a certain id too often using sessions.
So they click a button, which executes the following php code:
$id=$_GET["id"];
if ((isset($_SESSION["$id"]) && ((time() - $_SESSION["$id"]) > 180)) || (!isset($_SESSION["$id"]))) {
// last vote was more than 3 minutes ago
$_SESSION["$id"] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
So I'm creating a session variable for each question id which holds the time() of their last vote. I would do this with cookies, but they can be disabled.
Currently, there is a bug somewhere with my logic, because it allows the user to keep clicking the button and adding as many votes as they want.
Can anyone see an error that I have made?
using sessions to prevent multiple voting makes very little sense.
sessions do use cookies with the same drawbacks
unlike strings, variables in PHP should be addressed without quotes. such a false usage WILL cause an error someday.
I see no point in checking for isset($_SESSION[$id]) twice.
There was a bug in PHP which disallowed numerical indices for the $_SESSION array. Dunno if it was corrected nowadays.
As it was pointed out by Sajid, you have to call session_start() before using $_SESSION array.
now to the logic.
to me, it seems the code won't let anyone to vote at all. as it won't pass isset($_SESSION[$id]) condition for the first time and won't let $_SESSION[$id] to be set and so on.
it seems correct condition would be
if ( (!isset($_SESSION['vote'][$id]) OR (time() - $_SESSION['vote'][$id]) > 180) )
You need to call session_start() to start the session before any headers are sent. Otherwise, sessions will not be enabled unless the ini setting to autostart sessions is on. Also, your server must be correctly configured to be able to store session files (usually a writable tmp dir is needed). See more about sessions here: http://www.php.net/manual/en/ref.session.php
There might be a problem with the if statement. Try the following
$id=$_GET["id"];
if (((isset($_SESSION[$id]) && ((time() - $_SESSION[$id]) > 180))) || (!isset($_SESSION[$id]))) {
// last vote was more than 3 minutes ago
$_SESSION[$id] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
Perhaps time() returns milliseconds and you should compare to 180000 instead of 180.

PHP - consecutive page visits

my question is simple : How can I count how many consecutive days visitor have visited my site (php), any ideas are welcome.
Simple:
Just have some concept of either logging in, or a persistent cookie (logging in is more reliable since they can clear cookies). Then in your database have a field for "last logged in". If the last logged in field matches yesterday's date, increment your consecutive visit count, otherwise reset it.
EDIT: it's probably obvious, but make sure you update the "last logged in" field after you check it to be today, otherwise every time they load the page it'll increment the count!
EDIT: a quick example may look something like this (psuedo code):
// first you need to set $last seen from the DB..
// first you need to set consecutive from the DB too..
// once you have, you can do something like this.
if(strtotime('-1 day', date('Y-m-d')) == $last_seen) {
$consecutive = $consecutive + 1;
mysql_query(sprintf('UPDATE user SET last_seen=NOW(),consecutive=%d WHERE id=%d', $consecutive + 1, $id));
} else if(date('Y-m-d') == $last_seen) {
// ok, they logged in today again, do nothing.
} else {
$consecutive = 0; // only really needed if you plan on displaying it to the user
// later in this script
mysql_query(sprintf('UPDATE user SET last_seen=NOW(),consecutive=0 WHERE id=%d',$id));
}
cookies
if(isset($_COOKIE["identifier"])){
// log as existing user
}else{
setcookie('identifier', $id_value, ...
}
It wont work if people clear there cookies, which is why they clear cookies.
You can use pluggable traffic analitic tools, commercial or less like Google Analitics.

Categories