Cookie value not incrementing in PHP - php

For some reason I'm trying to have my "else" statement increment the amount of times the person has been to my website and it's not incrementing correctly. When I run my php, all it does it increment it once, after that, there are no more refreshes and the $cookieValue just keep echoing 2 instead of 3,4,5,6... What am I missing here?
<?php
date_default_timezone_set('EST');
if (!isset($_COOKIE["time"])) {
$cookieValue = 1;
setcookie("time", $cookieValue, time()+(86400*365));
}
$cookieLastVisit = date(DATE_RFC1036);
setcookie("lastVisit", $cookieLastVisit, time()+(86400*365));
?>
<html>
<head>
<title>Question 2</title>
</head>
<body>
<?php
if ($cookieValue == 1){
echo ("Welcome to my webpage! It is the first time that you are here.");
} else {
$cookieValue = ++$_COOKIE["time"];
echo("Hello, this is the " . $_COOKIE["time"] . " time that you are visiting my webpage. Last time you visited my webpage on: " . $cookieLastVisit . " EST");
$visit = date(DATE_RFC1036);
setcookie("lastVisit", $visit);
}
?>
</body>
</html>

Move the setting of the cookie time var to the same place as the declaration.
<?php
date_default_timezone_set('EST');
if (!isset($_COOKIE["time"])) {
$cookieValue = 1;
} else {
$cookieValue = ++$_COOKIE["time"];
}
setcookie("time", $cookieValue, time()+(86400*365));
$cookieLastVisit = date(DATE_RFC1036);
setcookie("lastVisit", $cookieLastVisit, time()+(86400*365));
?>
<html>
<head>
<title>Question 2</title>
</head>
<body>
<?php
if ($cookieValue == 1){
echo ("Welcome to my webpage! It is the first time that you are here.");
} else {
echo("Hello, this is the " . $_COOKIE["time"] . " time that you are visiting my webpage. Last time you visited my webpage on: " . $cookieLastVisit . " EST");
// you can't set cookie after you've output to the browser :/
//$visit = date(DATE_RFC1036);
//setcookie("lastVisit", $visit);
}
?>
</body>
</html>

You need to set the value of the cookie. The change to the $_COOKIE variable doesn't save the value of the cookie in "the next" page
else {
$cookieValue = ++$_COOKIE["time"];
setcookie("time", $cookieValue, time()+(86400*365));
...
}

Related

PHP functions not giving the expected output

I am new to php so can anyone tell me why when I open the HTML, it is not showing “5! is 120” as it should be and am instead getting:
Applications
", $num, "! is ", factorial ($num), ".
"; } else { echo "
Please enter a positive integer.
"; } echo "
Return to the Entry Page
"; ?>
PHP functions
<?php
function isPositiveInteger ($n) {
$result = false;
if (is_numeric($n))
if ($n == floor($n))
if ($n>0 )
$result = true;
return $result;
}
function factorial ($n) { // declare the factorial function
$result = 1; // declare and initialise the result variable
$factor = $n; // declare and initialise the factor variable
while ($factor > 1) { // loop to multiple all factors until 1
$result = $result * $factor;
$factor--; // next factor
} // Note that the factor 1 is not multiplied
return $result;
}
?>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="product" />
<meta name="keywords" content="HTML5, tags" />
<meta name="author" content="Ib" />
<title>Product</title>
</head>
<body>
<?php
include ("mathfunctions.php");
?>
<h1> Applications </h1>
<?php
$num=5;
if (isPositiveInteger($num)) {
echo "<p>", $num, "! is ", factorial ($num), ".</p>";
} else {
echo "<p> Please enter a positive integer. </p>";
}
echo "<p> <a href='factorial.html'> Return to the Entry Page </a></p>";
?>
</body>
</html>

PHP cookie visit counter not working

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!";
}
?>

How to compare the time in from the nearest scheduled time

can someone please help me how to fix this code. What I need is to let the current time compare it to the nearest saved schedule in the column "from"
because the current time is only comparing it to the first added schedule
code:
<?php
//Include the database configuration
include 'config.php';
//Get the data of the selected teacher
$teacher = $dbconnect->prepare("SELECT * FROM time WHERE IMEI = ? AND NFC = ?");
$teacher->bindValue(1,$_GET['IMEI']);
$teacher->bindValue(2,$_GET['NFC']);
$teacher->execute();
//Get the data
$time = $teacher->fetch();
//Store the current time
$current_time = new DateTime();
//Placeholder variables
$time_difference = 0;
$remark = "";
//If there is such a teacher let the teacher enter
if(!empty($time))
{
//Get the time difference
$time_difference = round( (strtotime($current_time->format('H:i:s')) - strtotime($time['From'])) / 60 );
//Check if the professor is late or not
//If the time difference is negative he/she is early
if($time_difference < 0)
{
$remark = 'Sir why are you so early?';
}
//If the prof is on time which is 0 time difference or less than 15 minutes
else if($time_difference == 0 || $time_difference < 15)
{
$remark = "Sir it's a miracle you are on time";
}
//Oh come on why are you so late Sir?Porn marathon at night?
else if($time_difference == 15 || $time_difference > 15)
{
$remark = 'Sir why are you late?';
}
$time_in = $dbconnect->prepare("INSERT INTO time_in (teacher_id,name,NFC,IMEI,time_in,remarks) VALUES (?,?,?,?,?,?)");
$time_in->bindValue(1,$time['teacher_id']);
$time_in->bindValue(2,$time['name']);
$time_in->bindValue(3,$time['NFC']);
$time_in->bindValue(4,$time['IMEI']);
$time_in->bindValue(5,$current_time->format('H:i:s'));
$time_in->bindValue(6,$remark);
$time_in->execute();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome!</title>
</head>
<body>
<h1>
<?php
//If there is such a teacher,welcome him/her
if(!empty($time))
{
echo 'Welcome '.$time['name'].'! Your NFC is '.$time['NFC'];
echo '</br>';
echo 'Time in at: '.$current_time->format('H:i:s');
//This is just a temporary display to show the time difference for testing.Kindly delete it later
echo '</br>';
echo 'Time difference: '.$time_difference;
//Display remark
echo '</br>';
echo 'Remark:'.$remark;
}
else
{
echo 'You are not registered.';
}
?>
</h1>
</body>
</html>

PHP echo text then sleep 10 seconds then echo another text

I've tried solutions from below links. But none of them give luck.
php-output-text-before-sleep
php-output-data-before-and-after-sleep
php-time-delay-using-ob-flush-with-loading-message
Actually below is my script.
<?php
include 'ini/INI.class.php';
$CompIP = $_SERVER['REMOTE_ADDR'];
$inidata = (parse_ini_file("guard.ini",true));
$atm = time()-$inidata["guard"][$CompIP];
if ($atm>60) { $atm = 1; }
echo "<p>You will be redirected to report page in <span id='counter'>" . $atm . "</span> second(s).</p>";
sleep($atm);
//my
//100
//line
//user report from mysql
$ini = new INI('guard.ini');
$ini->data['guard'][$CompIP] = time();
$ini->write();
?>
Still I get the whole content include 'You will be redirected to .......' after $atm (pause seconds) seconds.
My Workaround
<?php
include 'ini/INI.class.php';
$CompIP = $_SERVER['REMOTE_ADDR'];
$inidata = (parse_ini_file("guard.ini",true));
$atm = (time()-(isset($inidata["guard"][$CompIP]) ? $inidata["guard"][$CompIP] : 0));
if ($atm<60)
{
echo "<p>You will be redirected to report page in <span id='counter'>" . (60-$atm) . "</span> second(s).</p> <script type='text/javascript'> function countdown() { var j = document.getElementById('counter'); j.innerHTML = parseInt(j.innerHTML)-1; if (parseInt(j.innerHTML)<=0) { j.innerHTML = 0; location.href = 'tr.php'; } } for (i=1;i<=" . (60-$atm) . ";i++) { setTimeout(function(){ countdown(); },i*1000); } </script>";
} else { mysqlreport; $ini = new INI('guard.ini');
$ini->data['guard'][$CompIP] = time();
$ini->write();
}
?>
You can use JavaScript for this purpose and pass variables from PHP to JavaScript simply by writing the JavaScript code inside "echo". I think something like this will do the trick.
For redirection, the below example will give you an idea:
<?php
$url = "http://google.com";
$step = "1000";
$start = 12;
echo 'Redirection After <h1 id="counter">'.$start.'</h1> ';
echo '
<script>
var x = '.$start.';
setInterval(function(){
if(x==1){
window.location = "'.$url.'";
}
document.getElementById("counter").innerHTML = x;
x--;
}, "'.$step.'");
</script>';
?>
As for your content that you want to output, just place a tag and with JavaScript. Also, you can update it every 10 seconds; the technique is this, how you do it is up to you.

php outputs part of code without any echo

Here's my piece of code(full body code):
<body>
<script type='text/javascript'>
function AddEvent(Syear, Smonth, Sday, Eyear, Emonth, Eday, hallNumber){
...
}
</script>
<?php
function GetMonthByCoding($first , $second , $third) {
...
}
function GetDateByCoding($coding){
...
}
function GetDateFromLine($line){
...
}
$userid = '...';
$magicCookie = 'cookie';
$feedURL = "...";
$sxml = simplexml_load_file($feedURL);
foreach ($sxml->entry as $entry) {
$title = stripslashes($entry->title);
if ($title == "HALL") {
$summary = stripslashes($entry->summary);
$date = GetDateFromLine($summary);
echo ("<script type='text/javascript' language='JavaScript'> AddEvent(" . $date['start']['year'] . ", " . $date['start']['month'] . ", " . $date['start']['day'] . ", " . $date['end']['year'] . ", " . $date['end']['month'] . ", " . $date['end']['day'] . "); </script>");
}
}
?>
</body>
AddEvent() is JavaScript function defined earlier.
What I get in my browser is:
entry as $entry) { $title = stripslashes($entry->title); if ($title == "HALL") { $summary = stripslashes($entry->summary); $date = GetDateFromLine($summary); echo (""); } } ?>
Looks like it was an echo but as you can see there is no echo right in the middle of foreach.
Can anyone say what I am doing wrong?
PHP is not installed, or it is not enabled, or the file is not a .php file or the server has not been told to recognise it as a file to parse.
Try View Source and you should see all your PHP code. The only reason part of it shows up is because everything from <?php to the first > is considered by the browser to be an invalid tag.
I found the problem, it was in the name of variable sxml. I renamed it and the problem escaped.

Categories