PHP cookie visit counter not working - php

Hey I'm trying to make a counter of how many times someone is visiting my webpage and when it was the last time he visited. The last time visited is working fine.
I'm having a problem to display how many times he has been on the page however.
There's a bad display and it seems like I may be missing and incrementation somewhere but I can't seem to figure it out:
<?php
$Month = 3600 + time();
date_default_timezone_set('EST');
setcookie('AboutVisit', date("D M j G:i:s T Y"), $Month);
?>
<?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
$cookie = ++$_COOKIE['AboutVisit'];
echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
}
?>
EDIT: NEW CODE
<?php
$Month = 3600 + time();
date_default_timezone_set('EST');
setcookie('AboutVisit1', date("D M j G:i:s T Y"), $Month);
?>
<?php
if(isset($_COOKIE['AboutVisit1']))
{
$last = $_COOKIE['AboutVisit1'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
}
if(isset($_COOKIE['visitCount1'])){
$cookie = ++$_COOKIE['visitCount1'];
echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
setcookie('visitCount1');
}
?>

You will need 2 cookies, one for the date and one for the counter.
Also remember that cookies must be sent before any other output is sent to the browser, or they will be lost (and an error generated), so it would be better to store your messages in variables and output them once you have completed ALL cookie processing.
It would also be simpler to save the time() in the date cookie and format its output only for viewing on the page.
<?php
if(isset($_COOKIE['LastVisitDate']))
{
$msg1 = 'Welcome back! <br> You last visited on ' . date('d/m/Y H:i:s', $_COOKIE['LastVisitDate']) . '<br>';
} else {
$msg1 = "It's your first time on the server!";
}
setcookie('LastVisitDate', time(), time()+3600); // reset to now
if ( isset($_COOKIE['VisitCount']) ) {
$msg2 = "You have viewed this page {$_COOKIE['VisitCount']} times.";
setcookie('VisitCount', (int)$_COOKIE['VisitCount']+1, time()+3600 );
} else {
setcookie('VisitCount',1, time()+3600 );
$msg2 = 'Thanks for visiting, I hope you enjoy your first visit';
}
echo $msg1;
echo $msg2;
?>
Also note that cookies can be blocked, by the browser, so this is not a completely reliable method of tracking users.

You forgot to call setcookie(). Take a look at http://www.w3schools.com/php/func_http_setcookie.asp

Try This
<?php
if(isset($_COOKIE['AboutVisit']))
{
$last = $_COOKIE['AboutVisit'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
$value= $_COOKIE['AboutVisit']+1; //or whatever you wnt
setcookie("AboutVisit", $value);
echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
}
?>

Related

Update a cookie with a new one when visiting different pages

I have a website that has multiple locations and each location has their own set of information. When a user visits the main corp page, the location information will not display. When the user then goes to a location page I have a cookie being set.
$location_address = get_field('location_address','options');
$location_city = get_field('location_city','options');
$location_state = get_field('location_state','options');
$location_zip_code = get_field('location_zip_code','options');
$location_phone_number = get_field('location_phone_number','options');
// cookie will expire when the browser close
setcookie("locationAddress",$location_address);
setcookie("locationCity",$location_city);
setcookie("locationState",$location_state);
setcookie("locationZipcode",$location_zip_code);
setcookie("locationPhone",$location_phone_number);
The cookie is showing my location information in the firebug console. However, what is happening is when I go to another location, its grabbing both sets of cookies. I need it to replace the cookie previously set with the new one.
This is my code as well to output the cookie, which seems to be breaking as well:
<div class="top_contact">
<p><?php if(!isset($_COOKIE[$location_address])) { echo "" . $location_address . "";} ?>, <?php if(!isset($_COOKIE[$location_city])) { echo "" . $location_city . "";} ?> <?php if(!isset($_COOKIE[$location_state])) { echo "" . $location_state . "";} ?> <?php if(!isset($_COOKIE[$location_zip_code])) { echo "" . $location_zip_code . "";} ?> | <span class="top_phone"><?php if(!isset($_COOKIE[$location_phone_number])) { echo "" . $location_phone_number . "";} ?></span> </p>
</div>
You should set "path" argument in setcookie.
setcookie("locationAddress",$location_address, 0, "/");
setcookie("locationCity",$location_city, 0, "/");
setcookie("locationState",$location_state, 0, "/");
setcookie("locationZipcode",$location_zip_code, 0, "/");
setcookie("locationPhone",$location_phone_number, 0, "/");
If I were you I would probably try and set the path for the cookies.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
also, I spotted a few commas in your code and I fixed the spaghetti code.
<?php
echo '<div class="top_contact"><p>';
if(!isset($_COOKIE[$location_address]))
{
echo $location_address;
}
if(!isset($_COOKIE[$location_city]))
{
echo $location_city;
}
if(!isset($_COOKIE[$location_state]))
{
echo $location_state;
}
if(!isset($_COOKIE[$location_zip_code]))
{
echo $location_zip_code;
}
echo '<span class="top_phone">';
if(!isset($_COOKIE[$location_phone_number]))
{
echo $location_phone_number;
}
echo '</span> </p> </div>';
?>

PHP condition fails while using Session

I made a card game with PHP but there I'm facing some issue.
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
I'm getting an input from the user. The problem is, when the game loads at first, and the user enters an input and clicks submit, the game won't work. The condition ($_SESSION["bet"] != NULL) is giving true and bankroll is not defined.
Is there a way I can set this up properly? Is there some PHP method that can initialize the variable once then only works it on session start, then the rest of the code can take care of how that variable gets updated? The bankroll variable gets initialized if the user clicks submit without anything in it right now, so the game still works but it starts improperly.
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
The bankroll variable gets initialized to 1000 every time user submits a NULL input. I want to change this.
More code... Updating...
session_start();
$_SESSION["bet"] = $_POST["bet"];
echo "<br>";
//print_r($_SESSION);
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
else if ($_SESSION["bet"] > 1000 || $_SESSION["bet"] < 0)
{
echo " Please enter between 0 and 1000.";
}
else if ($_SESSION["bet"] > $_SESSION["bankroll"])
{
echo "You can't enter more than what you have.";
}
else
{
$deck = array();
for($x = 0; $x < 54; $x++) {
$deck[$x] = $x;
}
shuffle($deck);
//Then more stuff. This one for example...
if(($houseSuits[0] == -100) || ($houseSuits[1] == -100) || ($houseSuits[2] == -100) || ($houseSuits[3] == -100))
{
echo "<br>";
echo '<center> PLAYER WINS! (HOUSE HAS JOKER) </center>';
echo "<br>";
$_SESSION["bankroll"] = $_SESSION["bankroll"] + $_SESSION["bet"]; //THESE NEED TO BE ADDRESSED.
}
I JUST WANT TO FIND A WAY TO INITIALIZE BANKROLL TO 1000 AT START. THE WAY I'M DOING IT IS BY SUBMITTING A NULL VALUE THEN ASSUMING USER NEVER SUBMITS NULL VALUE AGAIN.
I WOULD LIKE BANKROLL TO BE INITIALIZED TO 1000, THEN FOR THE GAME TO TAKE CARE OF HOW BANKROLL GETS UPDATED.
I FOUND A WAY TO DO IT BUT IT'S NOT A PROPER WAY SO THAT'S WHY I'M ASKING FOR HELP.
THANK YOU.
Ok try this.
So if the bankroll is not set, then set it, once it's set it wont get set again because it's set.
Then any conditions after are fine.
session_start();
// Initialise bankroll if not already
if (!isset($_SESSION['bankroll'])) {
$_SESSION['bankroll'] = 1000;
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
}
$_SESSION['bet'] = $_POST['bet'];
if ($_SESSION['bet'] != NULL) {
echo "Your bet is: " . $_SESSION['bet'] . "<br>";
}
if ($_SESSION['bet'] > 1000 || $_SESSION['bet'] < 0) {
echo " Please enter between 0 and 1000.";
} elseif ($_SESSION['bet'] > $_SESSION['bankroll']) {
echo "You can't enter more than what you have.";
} else {
// Your card game stuff
}
Notes: you may have issues with using session as it'll store their bet wherever they are, so issuing a bet sets the session, then navigate elsewhere and come back and their bet will still be as before. Maybe this doesn't matter.
You also might not want to check if the bet is null, more perhaps empty or whatever. Test either way to be sure.

How to check past date should not be past from current date in PHP? in this second condition not working

My code is here,I am not able to perfect. when press submit button it check old date correct.. and shows "date must be in future" it correct. and whenever i put future date.. that time not show second alert instead it showing first.
if(isset($_POST['update']))
{
$pdata["card"] = $_POST['smcard'];
$pdata["expiry_date"] = date("Y-m-d" strtotime($_POST['smexdate']));
$dateone = $pdata["expiry_date"];
$nowdate = new DateTime();
if ($dateone < $nowdate)
{
echo "<script>";
echo "alert('date must be in future');";
echo "</script>";
}
elseif ($dateone > $nowdate)
{
echo "<script>";
echo "alert('Okay Good, Your date is in future');";
echo "</script>";
}
update_data('smartcard_data', $pdata, 'promotion_id='.$_REQUEST['promotion_id']);
exit;
}
Try below example to fine date passed or not
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');
if ( $dtA > $dtB ) {
echo 'dtA > dtB';
}
else {
echo 'dtA <= dtB';
}

Instagram API pagination in PHP

I am trying to create a small instagram app in PHP only (no database) and without getting an access_token (just my client_id). So far so good, (i.e. input user_id returns photos from last 30 days, with likes-count and created_time, in a table), until I get to pagination. As expected, I want to hit a 'more' button which loads next json file and adds additional photos to the existing table, but it falls apart there... Here is what I've got, working, except for the pagination attempt.
NOTE: this is an internal app, so the sensitivity of my client_id is not an issue, if it is exposed
<?php
if (!empty($_GET['user_id'])){
$user_id = ($_GET['user_id']);
$instagram_url = 'https://api.instagram.com/v1/users/' . $user_id . '/media/recent/?client_id=MY_CLIENT_ID';
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json, true);
}
?>
...
<?php
if(!empty($instagram_array)){
$instagram_array['pagination'] as $page { // Attempt at pagination
echo '<p>' .$page['next_url'].'</p>'; // Attempt at pagination
} // Attempt at pagination
foreach($instagram_array['data'] as $image){
if ($image['created_time'] > strtotime('-30 days')) {
echo '<tr>';
echo '<td>' . date('M d, Y', $image['created_time']) . '</td>';
echo '<td>'.$image['likes']['count'].'</td>';
echo '<td><img src="'.$image['images']['standard_resolution']['url'].'" alt=""/ style="max-height:40px"></td>';
echo '</tr>';
}
}
}
?>
</body>
</html>
Note: this is cobbled together from a few other sources - I am a total noob, so please forgive me if I need a little hand-holding...:)
You may specify min_timestamp to return medias which taken later than this timestamp
https://api.instagram.com/v1/users/{user_id}/media/recent/?access_token={access_token}&min_timestamp={min_timestamp}
$instagram_array['pagination']['next_url'] should be removed, it may include your access token which is a sensible data, that must be always invisible.
list_ig.php
<?
$user_id = "...";
$access_token = "...";
//30 day ago
$min_timestamp = strtotime("-30 day",time());
//pagination feature
$next_max_id = $_GET['next_max_id'];
$instagram_url = "https://api.instagram.com/v1/users/" . $user_id . "/media/recent/?access_token=" .$access_token. "&min_timestamp=" . $min_timestamp;
if($next_max_id != "")
$instagram_url .= "&max_id=" . $next_max_id;
$instagram_json = file_get_contents($instagram_url);
$instagram_array = json_decode($instagram_json ,true);
?>
<? if( $instagram_array['pagination']['next_max_id'] != "" ): ?>
More
<? endif;?>
.... print instagram data....
Instagram AJAX Demo
http://jsfiddle.net/ajhtLgzc/

PHP & MySQL - Compare IPs that are stored

I am trying to create a system to store the last logged on IP, and to compare it to the current IP, then do some functions later on down the road, but currently, I cannot compare them without going to the last else statement. Here's the code.
<?php
$userToPull = $session->userinfo['username'];
$query = "SELECT * FROM users WHERE username='$userToPull'";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)){
$userToShow = $row[25];
$IPtoVerify = $row[26];
}
$lastActivity = RelativeTime($userToShow);
$currIP = $_SERVER['REMOTE_ADDR'];
/*
Shows Partner Stuff
}elseif(!$session->isAdmin()){
echo "<div style='text-align:right;' id='homebox'";
echo "<b>Partner Total:</b> ".$database->getNumMembers()."<br>";
echo $database->num_active_users." partners logged in and ";
echo $database->num_active_guests." guests viewing the site.<br><br>";
echo "</div>";
*/
if(!$IPtoVerify == $currIP){
echo "<div style='text-align:right; background-color: #FAAAB3' id='homebox_partner'";
echo "<b>You are logged on from an unrecognized location.</b><br>";
echo "You will be sent a notification for security purposes.";
echo "<br>This location will automatically be remembered.";
echo "</div><br>";
}elseif($IPtoVerify == $currIP){
echo "<div style='text-align:right;' id='homebox_partner'";
echo "<b>You are logged on from a recognized location.</b><br>";
echo "Your IP is ".$_SERVER['REMOTE_ADDR'];
echo "<br>Your last login was approximately ".$lastActivity;
echo "</div><br>";
}else{
echo "<div style='text-align:right;' id='homebox_partner'";
echo "<b>An error has occurred.</b><br>";
echo "</div><br>";
}
?>
The only thing not working is the if(!$IPtoVerify == $currIP){ if statement.
The IP is stored in the normal fashion, and echo's like: 100.100.100.100. (normal fashion)
Maybe I am not comparing them right, but it has worked for me in the past.
This code doesn't do what you think:
if (!$IPtoVerify == $currIP) {
PHP interprets it as:
if ((!$IPtoVerify) == $currIP) {
You will want to write it as:
if ($IPtoVerify != $currIP) {
Try ($IPtoVerify !== $currIP) instead of (!$IPtoVerify == $currIP)
!$IPtoVerify == $currIP
means
0==$currIP,
because it first validates
`!$IPtoVerify`
which always returns 0 unless $IPtoVerify is 1.
Add additional brackets like
if(!($IPtoVerify == $currIP))...
to solve the issue.

Categories