PDA

View Full Version : Resolved Counter for dynamically generated pages/content



Beverleyh
03-03-2009, 11:28 AM
Hi,

I've been looking for a hit counter to display hits for dynamically generated content. Basically, a counter to say "this news article has been viewed X times".

I use a free script that generates news articles that are php included and displayed inside my main News & Updates page (the page is called "news.php").

I then found this counter script http://quickcount.uberm00.net/, hoping to add it inside the news article generater script and have an individual news article/page counter automatically generated and included on each dynamic news page.

I thought that the counter script would work as it already automatically creates new ids and new counters for other pages I add it to around the site, but not on the dynamically included news content/pages.

At the moment its showing the same count in each php included news article because they always form part of the outer "news.php" page.

Does anyone know how to alter this current counter script or of an alternative counter script that will work on dynamically included content that I can use instead?

thanks

Nile
03-03-2009, 10:37 PM
Can we see the code please? Also, do you want each file to have its own counter folder? Or do you want it all to be in one file, just each one is displayed as its own page(for example, page1 won't have the same amount of counts as page2?)

Please post a link to the page on your site that contains the problematic script so we can check it out.
Please include your code so that we can take a look at it, we can't do much without it.

Beverleyh
03-04-2009, 12:45 PM
Hi Nile,

Thanks for responding.

In answer to your questions, I would like all of the counts/hits to be logged in one file or database (I hate keeping track of many folders) and I would like each page (each news article) to have its own unique counter (to advise the visitor that "This article has been viewed X times").

The page in question is: http://jemcon.org/news.php. There's only one offical news article at the moment, called "2009 Fashion Design Contest", so click on the link to call it up.

Below is the php code that I use to generate news articles - this is called "dynamic_EasyPHPNews.php" and is added via a php include in my main "news.php" page - it works fine but I've added the code below in case you need to see it.
(Please note, the counter php include will go after this portion of code: "<? echo pullRating('$news_post_id',true,false,true); ?>", which is just an additional 5star rating function I added.
The counter php include is not currently in the news article page - I didnt want to add it until it works properly.)



<?
/* copywrited @EasyPHPNews , davehusk.com */
$max_posts = "5";
$news_dir = 'news_articles';
$news_post_summary = 'news_dynamic_summary.html';
//after adding new news attemp to load page name? if none will, show add again.
$_PAGE = '';
//ones below, blank if no, , use ?admin=news to add news
$max_posts_button = '';
$show_add_link = '';
$password = '';
$rempass = '1';
//coment out to not use the paging...or take out the 1
$paging = '1';
$paging_add_link_top = '1';
$paging_add_link_bottom = '1';
// end config, templates below, aprox line 51, 52

if (!is_dir($news_dir)){
echo "The dir <b>\"$news_dir\"</b> does not exist, make and chmod to 0777";
exit;
}

if(!isset($_SERVER['REQUEST_URI'])) {
if(isset($_SERVER['SCRIPT_NAME']))
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
else
$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'];
if($_SERVER['QUERY_STRING']){
$_SERVER['REQUEST_URI'] .= '?'.$_SERVER['QUERY_STRING'];
}
}

if ($_POST['Add']){

$c_passwd = eregi_replace("[^A-Z,0-9,_]", '', $_POST['passwd']);
if($c_passwd == $password){

$news_post_id = date("Y-m-d-H")."_".time(true);
$news_post_url = $news_post_id.".html";
$PostedBy = stripslashes($_POST['PostedBy']);
$news_body = preg_replace("/\\\'/","'",$_POST['news_body']);
$bs = "\\";
$f = "/$bs$bs$bs$bs/";
$r = $bs;
$news_body = stripslashes(preg_replace($f,$r,$news_body));
$summary = stripslashes($_POST['summary']);
$subject = stripslashes($_POST['subject']);
//templates
$summary_page = "<b><a href='SERVER_REQUEST_URI&view_news=$news_post_id'>$subject</a></b> <font size=1>($PostedBy)</font><br><font size=1>Summary: </font> $summary \n\n<br><BR>";
$news_post_body = "<table border='0' width='100%' cellPadding='0' cellSpacing='1' style='border:#ff0066 1px solid; margin:15px 0px'><tr><td style='padding:0px'><h1 style='margin:0px'>$subject</h1><div style='postition:absolute; width:877px; //width:884px; text-align:right; margin-top:-21px; color:white'>Published: $PostedBy</div></td></tr><tr><td style='padding:10px 15px'><!-- #BeginSnippet name='$PostedBy' -->$news_body<!-- #EndSnippet --></td></tr><tr><td align='center'><div style='width:100%; height:100%; border-top:1px solid #ff0066; padding:5px'><? echo pullRating('$news_post_id',true,false,true); ?></div></td></tr></table><br>";
function add_news_post($news_filename, $news){
global $subject, $date, $summary, $summaryp, $news_post_id, $news_body, $news_post_summary;
if(file_exists($news_filename)){
$fp = @fopen($news_filename, "r") or die ("Unable to open File $news_filename , check permissions");
$old_news = @fread($fp, filesize($news_filename)) or die ("Directory or File $news_filename not readable");
@fclose($fp);
}
$fp = @fopen($news_filename, "w");
@fwrite($fp, "<!--news_post-->\r\n$news\r\n$old_news") or die ("Directory or File $news_filename not writeable");
@fclose($fp);
}
if($subject != ""){
add_news_post("$news_dir/$news_post_summary", $summary_page);
add_news_post("$news_dir/$news_post_url", $news_post_body);
if($_PAGE) print '<html><head><META http-equiv="refresh" content="0;URL='.$_PAGE.'"></head><body></body></html>';
print 'Your News Article has been added. Please <B><A href="'.$_SERVER['PHP_SELF'].'" target="_top">Refresh</A></B> the page.<br><br> ';
}
} else {
echo '<p><b> Password is wrong! </b><br><br>';
}
}

if($_GET['admin']=="news") {
if($rempass)
$rempass2 = 'value="'.$_POST['passwd'].'"';
?>
<b>Add A News Article</b><br><br>
<form action="<?=$_SERVER['REQUST_URI'];?>" method="post">
<table border=0>
<input type=hidden name='passwd' <?=$rempass2?> size=50>
<tr> <td align="right"> <b>News Headline:</b> </td><td> <input type=text name="subject" size=50> </td></tr>
<tr> <td align="right"> <b>Date Published:</b> </td><td> <input size="50" name='PostedBy' value="<? echo date("F jS\, Y"); ?>"> </td></tr>
<tr> <td align="right" valign="top"> <b>News Summary:</b> </td><td> <textarea name="summary" rows=5 cols=50 wrap=soft></textarea> </td></tr>
<tr> <td align="right" valign="top"> <b>News Article:</b> </td><td> <textarea name="news_body" rows=15 cols=50></textarea> </td></tr>
<tr> <td align="right"> <b>&nbsp;</b> </td><td align="center"> <input type=submit name=Add value=Add&nbsp;News&nbsp;Article> </td></tr>
</table>
</form><br>
<?
} else
if (is_numeric($_POST['posts_max']))
$max_posts = $_POST['posts_max'];
elseif(is_numeric($_GET['pmax']))
$max_posts = $_GET['pmax'];
if($max_posts)
$pmax = 'pmax='.$max_posts;

print '<table width=100% border=0 cellspacing=1 cellpadding=1>';
$news_summaryf = $news_dir.'/'.$news_post_summary;
if(is_file($news_summaryf)){
$fh = @fopen($news_summaryf, "r") or die('Unable to open summary page...');
$old_news = @fread($fh, filesize($news_summaryf)) or die('Unable to read summary page...');
@fclose($fh);
$news_posts = explode("<!--news_post-->", $old_news);
$idv = 0;
$Page = $max_posts;

if($paging){
$pmax .= '&';
$Counted = count($news_posts);
$TotalPages = ceil( ($Counted - 1) / $max_posts);
//what page are we on?
if (is_numeric($_GET['P']) > 0)
$CurrentPage = $_GET['P'];
else
$CurrentPage = 1;

unset($Page_Numbers);

if($CurrentPage > 1)
$Page_Numbers = " <a href=\"?".$pmax."P=". ($CurrentPage - 1) ."\">&laquo; Previous</a> ";

for($x=1; $x < $TotalPages + 1; $x++) {
if ($x == $CurrentPage && $CurrentPage > 0)
$Page_Numbers .= ' <b> ' . $x . ' </b> | ';
else
$Page_Numbers .= ' <a href="?'.$pmax.'P='.$x.'">'.$x.'</a> | ';
}

if($CurrentPage < $TotalPages )
$Page_Numbers .= " <a href=\"?".$pmax."P=". ($CurrentPage + 1) ."\">Next &raquo;</a>\r\n ";
else $Page_Numbers = rtrim($Page_Numbers," |");

//echo 'Total:'. ($Counted - 1) .' <br>';
if($paging_add_link_top && $Page_Numbers)
echo '<tr><td colspan=2><font size=-3>Page(s): '.$Page_Numbers.'</font><br><br></td></tr>';

if($CurrentPage > 1)
$Page = ($CurrentPage) * $max_posts;
else
$Page = $max_posts;
$idv = $Page - $max_posts +1;

}

if(is_numeric($_GET['P']))
$P = 'P='.$_GET['P'];

echo '<tr><td valign="top" width=100%>';


for ($i = $idv; $max_posts; $i++) {
if ($i > $Page) {
break;
}
//SERVER_REQUEST_URI
$_SERVER_REQUST_URI = '?'.$pmax.$P;
$news_post = str_replace("SERVER_REQUEST_URI",$_SERVER_REQUST_URI,$news_posts[$i]);
echo $news_post;
unset($news_post);
}
// echo '</td>';

} else echo 'Summary page not found ' . $news_summary;

echo '</td></tr><tr><td width="100%" valign="top">';
if($_GET['view_news'])
if (!@include ($news_dir . '/' .$_GET['view_news']. '.html')) echo 'News not found';

echo '</td></tr>';

if($paging_add_link_bottom && $paging && $Page_Numbers)
echo '<tr><td colspan=2><font size=-3>Page(s): '.$Page_Numbers.'</font></td></tr>';

if ($max_posts_button)
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post"><tr><td width=20%><input name=posts_max size=3 value=5><input type=submit name=posts value=Posts></td></tr></form>';

if ($show_add_link)
echo '<tr><td width=20%><br><a href=?admin=news>Add A News Article</a></td></tr>';
?>
</tr>
</table>
<!---------------@EasyPHPNews , easyphpscripts.com------------------>


My post original post exceeded the forum character limit so i'll continue in the next one...

Beverleyh
03-04-2009, 12:47 PM
Continued from previous post...

Now here's the first script for the counter, "quickcount.php" - 3 more script files follow and are within a directory called "includes":


<?php

// QuickCounter v1.0
// Copyright (c)2006 Jamie Arseneault, All Rights Reserved
// Quickly and automatically generates a counter for a page.

// Permission is given to use and redistribute this code under the terms of
// the GNU General Public License v2.0, viewable online at
// http://www.gnu.org/licenses/gpl.html

// security token
define('IN_QUICKCOUNT', true);

// common include
require "includes/common.php";

// is there a counter for this page?
$query = "
SELECT count
FROM quickcount
WHERE url='".$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME']."'";
$count = aquery_first_cell($query);

if($count === false)
{
// create counter for this page in table
$query = "
INSERT INTO quickcount
(
url,
count
)
VALUES
(
'".$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME']."',
1
)";
db_query($query);

$count = 1;
}
else
{
// increment counter
$query = "
UPDATE quickcount
SET count = count + 1
WHERE url = '".$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME']."'";
db_query($query);
$count++;
}

echo $count;

?>




Here's the "includes/common.php" file:



<?php

// QuickCounter v1.0 [common include]
// Copyright (c)2006 Jamie Arseneault, All Rights Reserved
// Quickly and automatically generates a counter for a page.

// Permission is given to use and redistribute this code under the terms of
// the GNU General Public License v2.0, viewable online at
// http://www.gnu.org/licenses/gpl.html

// security check
if(!defined('IN_QUICKCOUNT'))
die('Access denied.');

$includes_dir = dirname(__FILE__);

// common functions
require $includes_dir."/functions.php";

// user config
require $includes_dir."/config.php";

// connect to database
$dblink = mysql_connect($host, $user, $pass);
mysql_select_db($db, $dblink);

// does the QuickCount schema exist?
$query = "
SHOW TABLES LIKE 'quickcount'";
$tableexists = aquery($query);

if(!$tableexists)
{
// quickinstall schema
$query = "
CREATE TABLE `quickcount`
(
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`url` TEXT NOT NULL,
`count` INT NOT NULL
) TYPE = MYISAM COMMENT = 'QuickCount counter table.'";
if(!db_query($query))
{
die('Schema not installed and unable to automatically create. Check MySQL user privileges.');
}
}

?>


Here's the "includes/config.php" file:


<?php

// QuickCounter v1.0 [common include]
// Copyright (c)2006 Jamie Arseneault, All Rights Reserved
// Quickly and automatically generates a counter for a page.

// Permission is given to use and redistribute this code under the terms of
// the GNU General Public License v2.0, viewable online at
// http://www.gnu.org/licenses/gpl.html

// database setup
$host = "localhost";
$db = "quickcount";
$user = "username";
$pass = "password";

?>


Lastly, here's the "includes/functions.php" file:


<?php

// QuickCounter v1.0 [common functions]
// Copyright (c)2006 Jamie Arseneault, All Rights Reserved
// Quickly and automatically generates a counter for a page.

// Permission is given to use and redistribute this code under the terms of
// the GNU General Public License v2.0, viewable online at
// http://www.gnu.org/licenses/gpl.html

// simple query abstraction
function db_query($query)
{
$results = mysql_query($query);
if(!$results)
{
echo "<span style=\"color: red; font-weight: bold;\">SQL query failed:<br />".$query."<br />With error:<br />".mysql_error()."<br /><br /></span>";
return false;
}
else
{
return $results;
}
}

// given a SELECT query, return an array of rows returned
function aquery($query)
{
$results = db_query($query);
if(!$results || mysql_num_rows($results) == 0)
{
return false;
}
else
{
$rows = array();
while($row = mysql_fetch_assoc($results))
{
$rows[] = $row;
}
return $rows;
}
}

// given a SELECT query, return the first row returned
function aquery_first($query)
{
$results = db_query($query);
if(!$results || mysql_num_rows($results) == 0)
{
return false;
}
else
{
return mysql_fetch_assoc($results);
}
}

// given a SELECT query, return only the first cell
function aquery_first_cell($query)
{
$results = db_query($query);
if(!$results || mysql_num_rows($results) == 0)
{
return false;
}
else
{
$row = mysql_fetch_row($results);
return $row[0];
}
}

?>

So, just to confirm, the hit counter script automatically generates a new id for every page its included in. In my case, the id is always for the main news.php page and not the individual news articles content inserted/called via a php include, which is how I would like it to work (to it shows views/hits per article.)

I hope this is sufficient information for you Nile.
If you would like any other clarification, please let me know.

Thanks for any help you can offer me.

Beverley

Nile
03-05-2009, 04:09 AM
Ok, is it possible to use a mysql database instead of files? (I see that you have mysql)

Beverleyh
03-05-2009, 08:55 AM
Hi Nile,

Yes, a mySQL database would actually be my preferred choice - Sorry I should have clarified that before.

Just stumbling through and trying to use some logic...
The "dynamic_EasyPHPNews.php" file (and 5star rating funtion within it) uses a unique news article id/variable '$news_post_id' - maybe that could be used as, or part of, the unique id for the counter instead of the page url which I think is what's its currently doing? I'm not sure how to do that though or if its relevant. As you can probably tell, I have very little php knowledge so I'm probably looking for patterns where there arn't any. Anyhow Nile, your guidance is very much appreciated.

Let me know if you need anything else from me.

Thanks

Beverleyh
03-05-2009, 11:49 AM
I sussed it Nile!

I changed all references of ' ".$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME']." ' to ' ".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']." ' in the quickcount.php file.
Now the script generates an id similar to " www.jemcon.org/news.php?pmax=5&&view_news=2009-02-27-21_1235769160 " instead of just " www.jemcon.org/news.php ", giving a unique id for every news article in the database.

Its amazing what a bit of sleep does for logic and Google searches ;)

Thanks for taking the time to reply to me though.

Nile
03-05-2009, 01:05 PM
Haha. Glad to help (I wasn't much help :D).

It seems your topic is solved... Please set the status to resolved.. To do this:
Go to your first post ->
Edit your first post ->
Click "Go Advanced" ->
Then in the drop down next to the title, select "RESOLVED"