I have the following script which creates a cookie and updates a site counter in a database record if the user hasn't visited the website in a day, else, it will just display the current count of visits. Currently the cookie is displaying NULL every time I reload the index page and therefore the table keeps getting updated more than it should. How do I maintain the cookie value on the index page when this script is included?
if (empty($_COOKIE["visits"])) {
// increment the counter in the database
mysql_query("UPDATE visit_counter ".
" SET counter = counter + 1 ".
" WHERE id = 1");
/* Query visit_counter table and assign counter
value to the $visitors variable */
$QueryResult = mysql_query("SELECT counter ".
" FROM visit_counter WHERE id = 1");
// Place query results into an associative array if there are any
if (($row = mysql_fetch_assoc($QueryResult)) !== FALSE) {
$visitors = $row['counter'];
} else {
// else if this is the first visitor set variable to 1
$visitors = 1;
}
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24));
} else {
$visitors = $_COOKIE["visits"];
}
The cookie script is included in an index file, so the following would be the index file...
<?php include("Includes/cookie.php"); ?>
var_dump($_COOKIE["visits"]); /* Always returns NULL on this page but
returns the cookies real value if
run straight from cookie.php script */
/* Some main page content goes here */
/* The cookie value is echoed in the footer file that is included by
creating a statement that says echo "total visitors: ".$visitors; */
<?php include("Includes/footer.php"); ?>
The problem is on set_cookie
set it from:
<?php
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24));
?>
to
<?php
// Set cookie value
setcookie("visits", $visitors, time()+(60*60*24),'/'); // Define the cookie path to be used on this domain
?>
Good luck
Related
I want to use sessions to track unique page views. Not a very robust method, I know, but sufficient for what I want to do.
On the first page load the session variable is set and a field in the database increments. On subsequent page views it does not increment, because the increment is conditional on the session variable not being set.
This is my code:
$pagenumber = 1;
//other stuff here...
session_start();
if (!isset($_SESSION[$pagenumber])) {
$storeview = mysqli_query($dbconnect, "UPDATE tblcount SET views=views+1 WHERE id='$pagenumber'");
$_SESSION[$pagenumber] = $pagenumber;
}
echo $_SESSION[$pagenumber];
$Recordset1 = mysqli_query($dbconnect, "SELECT views FROM tblcount WHERE id = '$pagenumber'");
$row_Recordset1 = mysqli_fetch_assoc($Recordset1);
echo "Viewed ".$row_Recordset1['views']." times";
The first echo is only there for testing. It echoes the value just fine on page refresh and the increment works the first time, but the view count continues to increment on every page refresh, which it shouldn't. I can't see why.
I found a similar question:
PHP: Unique visits/hits to specific items using cookies/ip but I ran into a similar issue with the solution offered there.
Help appreciated!
Problems:
You are updating in tblCount EACH time, because your session is closed each time your script finishes.
SO: Put the session_start()call as the FIRST LINE in code.
It's not permitted to set an integer as $_SESSION variable. So if you set $_SESSION[$pagenumber] = 'something', then you gain the following notice:
( ! ) Notice: Unknown: Skipping numeric key 1 in Unknown on line 0
Quite... not understandable. For details see this answer.
Solution:
Add your $pagenumber as index in an array (here pagenumbers) and that array inside the $_SESSION variable. No notice anymore.
session_start();
$pagenumber = 1;
if (!isset($_SESSION['pagenumbers'])) {
$_SESSION['pagenumbers'] = array();
}
if (!isset($_SESSION['pagenumbers'][$pagenumber])) {
updateViews($pagenumber);
$_SESSION['pagenumbers'][$pagenumber] = $pagenumber;
}
echo 'Page number: ' . $_SESSION['pagenumbers'][$pagenumber] . '<br/>';
$views = getViews($pagenumber);
echo '<pre>Viewed ' . print_r($views, true) . ' times</pre>';
Note: I used my functions to test. They just replace your db-processing code.
Just tested. This also works.
session_start();
// Get page name
$page_url = $_SERVER['REQUEST_URI'];
// Create the session ID. Will act as visitor username
if(!isset($_SESSION['id'])){
$_SESSION['id'] = session_id();
// For the visit to the first page
$visit_id = $_SESSION['id'];
}else{
// For subsequent visits to any page
$visit_id = $_SESSION['id'];
}
/******************
Query DB. Insert only one visit per page per session.
It means we need a count for each page to get its total visits.
Or a count for all records to get site total visits.
************************************/
$query_visits_table = mysqli_query($db_connect, "SELECT * FROM tblcount WHERE (visit_id='$visit_id') AND (page_name='$page_url')");
if(mysqli_num_rows($query_visits_table) > 0){
// Do nothing if this page has been visited during this session
}else{
mysqli_query($db_connect, "INSERT INTO tblcount (visit_id, page_name, visit) VALUES('$visit_id', '$page_url', '1')");
}
// Get site total visits
$query_site_visits = mysqli_query($db_connect, "SELECT * FROM tblcount");
// For a specific page
$query_specific_page_visit = mysqli_query($db_connect, "SELECT * FROM tblcount WHERE page_name='$page_url'");
if(isset($query_site_visits) && isset($query_specific_page_visit)){
$site_total_visits = mysqli_num_rows($query_site_visits);
$specific_page_visit = mysqli_num_rows($query_specific_page_visit);
echo 'Site total visits is '. $site_total_visits . '<br />';
echo 'Total visits for ' . $page_url . ' is ' . $specific_page_visit;
exit();
}
I have a login page and if error occurs in login such as wrong data inserted, it will says wrong data inserted. However my problem is that I can login but it displays blank page for rows with null value in a row instead of a menu bar.
I can login for both rows but my homepage appears as blank page for staff_id = 12 which i think it is caused by the null value in stf_superior column.
I want every user can view the content of the homepage even if their stf_superior is null.
I dont know where the main problem is since the error says :
and my home.php got no sql at all. so i assume it must be in my login_process.php because it seems like it couldnt receive the id for row = 12 (which row contains null value in stf_superior column).
Below is my Login_Process.php
<?php
require_once('include/connection.php');
require_once('include/userGlobal.php');
if($_POST['STAFF_ID']== "" ||$_POST['LOGIN_PASSWORD']=="") {
echo "<script language=\"javascript\">alert(\"Username & password required!\");
document.location.href='index.php';</script>";
}
else{
$sql="SELECT * FROM staff where staff_id='".$_POST['STAFF_ID']."' ";
//$result = mysql_query($sql, $connection) or die(mysql_error());
$result = DB_Query($sql);
//$staffRow=mysql_fetch_array($result);
$staffRow=DB_FetchRow($result);
$the_id=$staffRow["staff_id"];
$the_pass=$staffRow["staff_pass"];
$the_status=$staffRow["stfs_id"];
//$passs = base64_encode($_POST["LOGIN_PASSWORD"]);
$passs = ecdPwd($_POST["LOGIN_PASSWORD"]);
$level = $staffRow["staff_lvl"];
if(($the_id == $_POST["STAFF_ID"])&&($the_pass == $passs) ){
//success
//update last login
$sql_stfl="SELECT * FROM staff_login where staff_id='".$the_id."'";
$rs_stfl = DB_Query($sql_stfl);
if (DB_RowsReturned($rs_stfl) > 0){
//update entry
$row = DB_FetchRow($rs_stfl);
$prevLogin = $row["stfl_last_login"];
$sql_update = "UPDATE staff_login SET stfl_prev_login='{$prevLogin}' WHERE staff_id='{$the_id}'";
DB_Query($sql_update);
} else {
//create entry
$sql_insert = "INSERT INTO staff_login (staff_id) VALUES ('{$the_id}')";
DB_Query($sql_insert);
}
setcookie("id",$_POST["STAFF_ID"]);
header("Location:Home.php");
}
else{
//reject
echo "<script language=\"javascript\">alert(\"WRONG USERNAME/PASSWORD!\");
document.location.href='index.php';</script>";
header("Location:index.php");
}
}
?>
<?php ob_flush(); ?>
I have a PHP search function which retrieves items from my database and displays them on a search results page. When clicking on a search result, it currently takes you to a separate html page (for each search item) which contains further details about the item.
I would like to link each search result to one PHP page which gets the item ID from the URL and then retrieves and displays the relevant data from the database.
Below is the PHP code from the page which displays the search results, but I am not sure where to edit this, to link each item to the dynamic PHP page and then retrieve the ID from the URL on the dynamic PHP page?
<?php
if (!empty($data)){
foreach ($data as $item){
echo '<div class="item">';
if (strlen($item['item_image']) > 10){
if(strlen($item['item_link']) > 10){
echo '<a href="'.$item['item_link'].'">';
}
else {
echo '<div class="fail ">No Results Found;
}
?>
Edit:
I have used the below code on the detail_page.php
<?php $db =
mysql_connect("","","") or die("Database Error");
mysql_select_db("items",$db); $id = $_GET['id']; $id = mysql_real_escape_string($id); $query = "SELECT * FROM `items-one` WHERE `id`='" . $id . "'"; $result = mysql_query($query);
But now need to call all of the row fields from the ID in the database and then add them at various points throughout the page?
Typically this is done by passing an id in a parameter via GET. So links on the listing page may look like this:
echo '' . $link_text . '';
Here $id and $link_text maybe be populated in loop or whatever.
On /path/to/detail_page.php page you would have some code like this:
// validate that there is an integer-like value passed in `$_GET['id']`
// if so, set value to $id
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
// see results of filtering and behave accordingly
if (is_null($id)) {
// $_GET['id'] was not set
// do something and exit
} else if (false === $id) {
// the value at $_GET['id'] didn't pass validation filter
// do something and exit
}
// $id has a good integer value
// note you would probably need additional validation checks on the id value
// i.e. make sure value is not negative or 0
// you may want to cast $id to int to make these checks
// for example:
$id = int($id);
if ($id < 1) {
// bad $id value
// do something and exit
}
// read data from DB and display it
Below shows my coding to increment the number of publication view for my website. Right now it increments whenever I click refresh. I have used session command on some part of the code however it doesn't work, it increments whenever I click refresh. I want to understand how can I not make user to increment the session if they are in same session.
It will be very grateful if you can help me.
<?php
session_start();
$_SESSION['counted'] = true;
if (isset($_GET['id'])) {
$file_id = ($_GET['id']); //$id is a new vairable given value to the id selected in publication.php
if ($file_id <= 0) { //check if id is less than or equal to 0
die('The ID is invalid, please check the technical process!');
} else {
mysql_query("SELECT * FROM files WHERE id='$file_id'");
if (!isset($_SESSION['id'])) {
$_SESSION['id'] = 0;
$query = "UPDATE files SET visitors=visitors+1 WHERE id='$file_id'";
mysql_query($query);
mysql_close();
session_destroy();
}
}
}
?>
The reason it is incrementing each time you refresh is because of the following line of code:
session_destroy();
What it's doing is (as the name depicts) destroying your session after each increment, so next time the page loads, $_SESSION['id'] is no longer instantiated, so your if(!isset($_SESSION['id'])) always returns true.
You can try the following:
<?php
session_start();
$_SESSION['counted'] = true;
if (isset($_GET['id'])) {
$file_id = ($_GET['id']); //$id is a new variable given value to the id selected in publication.php
if ($file_id <= 0) { //check if id is less than or equal to 0
die('The ID is invalid, please check the technical process!');
} else {
mysql_query("SELECT * FROM files WHERE id='$file_id'");
if (!isset($_SESSION['id'][strval($_GET['id'])])) {
$_SESSION['id'][strval($_GET['id'])] = true;
$query = "UPDATE files SET visitors=visitors+1 WHERE id='$file_id'";
mysql_query($query);
mysql_close();
}
}
}
?>
I've used an array $_SESSION['id'] to store a key for each different page ID, then each time we test if we need to increment your counter, we check if an array key exists for that page, if it does, we don't increment.
Hope this helps! :)
I have a javascript for loop that sends an array to an ajax page to update the mysql database.
I echo the result back to the original page and it echos as a success but when I check the db nothing has changed
my javascript for loop that sends the array
for(var m=0; m<array.length; m++){
$.post("update_page_positions.php",{page_ref:array[m][0], ref:array[m][12], menu_pos:array[m][1], sub_menu_pos:array[m][2], top_menu:array[m][3], pagelink:array[m][4], indexpage:array[m][5], hidden:array[m][6], page_title:array[m][7], page_desc:array[m][8], page_keywords:array[m][9], page_name:array[m][10], deletedpage:array[m][11]},
function(data,status){
alert("data="+data+" status="+status);
});
here is the php ajax page the updates the db
<?
include("connect.php");
$ref = $_POST['ref'];
$page_ref = $_POST['page_ref'];
$menu_pos = $_POST['menu_pos'];
$sub_menu_pos = $_POST['sub_menu_pos'];
$top_menu = $_POST['top_menu'];
$indexpage = $_POST['indexpage'];
$page_name = $_POST['page_name'];
$page_title = $_POST['page_title'];
$page_desc = $_POST['page_desc'];
$page_keywords = $_POST['page_keywords'];
$hidden = $_POST['hidden'];
$pagelink = $_POST['pagelink'];
$deletedpage = $_POST['deletedpage'];
$query = mysql_query("SELECT * FROM pages WHERE ref='$ref' AND page_ref='$page_ref'");
if(mysql_num_rows($query)==0){
mysql_query("INSERT INTO pages(page_ref, ref, page_name, menu_pos, sub_menu_pos, top_menu, link, indexpage) VALUES('$page_ref','$ref','$page_name','$menu_pos','$sub_menu_pos','$top_menu','$pagelink','$indexpage')");
}
if($deletedpage=="1"){
mysql_query("DELETE FROM pages WHERE ref='$ref' AND page_ref='$page_ref'");
mysql_query("DELETE FROM site_content WHERE ref='$ref' AND page_ref='$page_ref'");
}
else{
if(mysql_query("UPDATE pages SET menu_pos='$menu_pos', sub_menu_pos='$sub_menu_pos', top_menu='$top_menu', indexpage='$indexpage', page_name='$page_name', page_title='$page_title', desc1='$page_desc', keywords_list='$page_keywords', hidden='$hidden', link='$pagelink' WHERE ref='$ref' AND page_ref='$page_ref'")){
echo "updated!";
} else{
echo "error";
}
}
?>
the INSERT and DELETE functions are fine but the UPDATE returns a success statement but does not update the db.
Can anyone see what the problem is?
Posted as an answer because the comment was too hard to read:
Rather than echoing "updated", try echoing
"UPDATE pages SET menu_pos='$menu_pos', sub_menu_pos='$sub_menu_pos', top_menu='$top_menu', indexpage='$indexpage', page_name='$page_name', page_title='$page_title', desc1='$page_desc', keywords_list='$page_keywords', hidden='$hidden', link='$pagelink' WHERE ref='$ref' AND page_ref='$page_ref'"
(ie. the query you're trying to run).
See if that gives you some clues.
UPDATE reports success, but does nothing in case when its WHERE clause rejects all rows in updated table.
Maybe $page_ref identifier is correct (so DELETE works), but full $page_ref and $ref combination is not?