I have a PHP script that initializes a session variable called ‘view’ to count page-views:
[php]<?php
session_start();
if (isset($_SESSION['views']))
$_SESSION['views']++;
else
$_SESSION['views'] = 1;
?>[/php]
I have a function that will be called from an input button that will unset the view variable:
[php]function reset_pageviews() {
unset($_SESSION[‘views’]);
}[/php]
Before I put that function in, the counter worked perfectly. After I put the function in, the counter worked once more then reset to 1 and would not change. I put an echo statement in the function so see if it was being called somehow and that was not the case. If I comment out the unset statement:
[php]function reset_pageviews() {
//unset($_SESSION[‘views’]);
}[/php]
Then the counter goes back to working. If I un-comment it, it goes back to 1 and doesn’t change. I have never seen this kind of behavior before and have googled for answers with no luck. Hope someone know what’s going on here. I’m fairly new to PHP so I think it’s probably human error somewhere but I can’t find the source. Here’s the full code for the page:
[php]
function foutput($filename, $title = "") {
$file = fopen($filename, "r") or die("Unable to open $filename!");
if ($title !== "")
echo "<b>" . $title . "</b><br>";
echo fread($file, filesize($filename));
fclose($file);
}
function foutput_lines($filename, $title = "") {
$file = fopen($filename, "r") or die("Unable to open $filename!");
if ($title !== "")
echo "<b>" . $title . "</b><br>";
// Output one line until end-of-file
while(!feof($file))
echo fgets($file) . "<br>";
fclose($file);
}
function foutput_chars($filename, $title = "") {
$file = fopen($filename, "r") or die("Unable to open $filename!");
if ($title !== "")
echo "<b>" . $title . "</b><br>";
// Output one line until end-of-file
while(!feof($file))
echo fgetc($file) . "<br>";
fclose($file);
}
function fwrite_to_file($filename, $lines) {
$file = fopen($filename, "w") or die("Unable to open $filename!");
foreach ($lines as $line)
fwrite($file, $line . "\n");
fclose($file);
}
$filelines = array(
"This is line 1",
"This is line 2"
);
fwrite_to_file("test.txt", $filelines);
function log_history() {
$file = fopen("history.txt", "w") or die("Unable to open history.txt");
fwrite($file, "Last visit: " . date("Y-m-d h:i:sa") . "\n");
fclose($file);
}
log_history();
function reset_pageviews() {
unset($_SESSION['views']);
}
?>
</head>
<body>
<h2>Homepage</h2>
<p><?php foutput_lines("Resources/webdictionary.txt", "Web-dictionary:"); ?></p>
<p><?php foutput_lines("test.txt", "Test:"); ?></p>
<p><?php foutput_lines("history.txt", "Site History:"); ?></p>
<p><?php echo "<b>Pageviews:</b><br>" . $_SESSION['views']; ?></p>
</body>
[/php]