Simple PHP click counter

Discussion in 'PHP' started by Dirty-Rockstar, Oct 5, 2006.

  1. #1
    Got a noobish site on the go and heres what i need. A click counter.

    theres a table with links. click the link and something loads on the same page. what i would like is a simple counter to show how many times a user clicked that link. Publicly, like next to the link. search engines are only telling me website counters. perferbly one that doesnt need a db. but i dont know if thats possible. Any help is greatly appriciated

    so its:

    {link here} [#] <---?
    {link here} [#] <---?
     
    Dirty-Rockstar, Oct 5, 2006 IP
  2. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #2
    You don't need a DB to have what you want, but it would make it much easier. Instead, you'd need to have the PHP script increment a variable in an external text file or PHP file.

    Here's how you could do it :)


    1. Firstly, make the link's URL point to a .php script that has the below code in it, and make sure the URL has ?clicked=1 on the end. So for example, say the .php file you make with the code in below is called "clickscript.php", make the URL to it via the link "http://www.yoursite.com/clickscript.php?clicked=1"

    2. Make a text file, php file and edit below by filling in their names.

    
    <?php
    
    // Check whether the link has been clicked
    $clicked = $_REQUEST['click'];
    
    // If it has, then read the file
    $filecontent = file('yourtextfile.txt');
    
    // Now we have your text file's content, get what variable is already there
    IF($filecontent > 0){
    
    // Turn variable into new variable
    $clicks = ($filecontent[0] + 1);
    
    // Variable in file is above 0 so lets add to it
    $file = "yourtextfile.txt";
    $Handle = fopen($File, 'w');
    $Data = "$clicks";
    fwrite($Handle, $Data);
    fclose($Handle);
    
    }ELSE{
    
    //There have been no clicks, so let's add one to the file
    $file = "yourtextfile.txt";
    $Handle = fopen($File, 'w');
    $Data = "1";
    fwrite($Handle, $Data);
    fclose($Handle); 
    
    }
    
    // Display total clicks
    ECHO "This link has been clicked $clicks times.";
    
    // Now take them to where ever the link should take them
    ECHO "<META HTTP-EQUIV='Refresh'
    CONTENT='0; URL=whereeverthelinkgoes.html'>";
    
    // End
    ?>
    
    PHP:
    (P.S. Let me know if the script works OK, then if it does, I'll give you some help with getting the number of clicks to display next to the links.)

    I pretty much rushed this together, but it should work :)

    Good Luck,

    Lee.
     
    BRUm, Oct 6, 2006 IP
  3. Pat Gael

    Pat Gael Banned

    Messages:
    1,331
    Likes Received:
    68
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Pat Gael, Oct 6, 2006 IP
  4. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    hmm, i looked over the code and i understand how it works i think, however the way i see it is (heh) the way i have this all set up it wont work. I only know html and really bad at that.

    Ive created a music station, I dont want to publicly post my site cuz it will make you laugh. heres what i did

    theres 2 tables
    each with a name of a song, when you click the link it grabs a html file. ok heres an example. I dont know how to enter raw code on this thread, im assuming it wont execute but im too tired to test it.so i replaced < > with {} (yes, im a noob)

    Table Header
    Name of song.link <---this points to {songname.html target ="targetname"}

    the somgname.html file has this in it

    {embed src="path/nameofsong.mp3" hidden="true" border="0" autostart="true" autoplay="true" loop="false" volume="100%"}

    which in turn plays on a hidden frame the frame looks like this

    {frameset cols="100%,*" border="0" framespacing="0" frameborder="0"}

    {frame src="path/musiclinkmess.php"}
    {frame src="path/hiddenmusicplayer.php" name="targetname"}
    {/frameset}

    what happens is that when you click a song link it plays it in the hidden frame. i needed the first link to point to a html file with the embed tag because if i didnt IE prompts and open/save option if it points the the .mp3 directly.(host doesnt like that ;) )

    and yes, i have to create a new page/new links and an individual html page with an embed tag to each song for EVERY song. i have 80 and counting, with complicated _top set up everywhere

    someone told me that it would be way easier to use a db to make this all work. I dont know php. It took me 2 months to make a guestbook out of templates.

    I think im at a loss.

    Its clever, ive been told. but way too much work :S
     
    Dirty-Rockstar, Oct 6, 2006 IP
  5. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #5
    My code I gave you should be pretty easy to implement. Just have the .php script to redirect to your .mp3 page. It can still function with the frames you have.
     
    BRUm, Oct 6, 2006 IP
  6. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Cool, Thanks. it will take me a few days to check it. I made a mess of my guestbook where Im trying to enter a break after X amount of characters. not working, i ll figure it out. I WILL try your code. and bump the topic if it goes *poof*

    I really appriciate the help.

    EDIT

    how can i have each individual link call the php page and direct it to where it needs to go. at the end of your script you have




    ECHO "<META HTTP-EQUIV='Refresh'

    CONTENT='0; URL=whereeverthelinkgoes.html'>";


    ?>

    inless i include functions and lable the links somehow. ugh, ill work on it. ill figure it out. thanks again
     
    Dirty-Rockstar, Oct 6, 2006 IP
  7. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #7
    Ah yeah good point. Have another variable in you URL, so it'd look like this:

    http://www.yoursite.com/clickscript.php?clicked=1&URL=www.example.com
    
    PHP:
    Then on the script I gave you, add this:

    
    
    $URL = $_REQUEST['URL'];
    
    
    PHP:
    Then replace the:

    
    ECHO "<META HTTP-EQUIV='Refresh' CONTENT='0; URL=whereeverthelinkgoes.html'>";
    
    PHP:
    to:

    
    ECHO "<META HTTP-EQUIV='Refresh' CONTENT='0; URL='.$url.'>";
    
    PHP:
    Hope that helps :)

    Lee.
     
    BRUm, Oct 6, 2006 IP
  8. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #8
    not to be a drag, but im super super new to php. i can read it but not in pieces. could you please show me the code in full with the new part. ill know how to fill it out if you do that

    thanks

    edit, nevermind i understand

    thanks ill try it soon

    edit:forget my last statement, im super lost :S
     
    Dirty-Rockstar, Oct 6, 2006 IP
  9. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #9
    WOOT

    figured it out

    // Check whether the link has been clicked
    4.
    $clicked = $_REQUEST['click'];
    5.
    $URL = $_REQUEST['URL'];

    it all makes sense now. ill get back to you
     
    Dirty-Rockstar, Oct 6, 2006 IP
  10. GoglGourd

    GoglGourd Active Member

    Messages:
    122
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #10
    <?
    //////////////////////
    // Inspired/Thought of by Chuckun, created by GoglGourd
    // goglgourd@gmail.com msn or email
    // www.myLBFH.co.uk
    // Best viewed with Crimson Editor: www.crimsoneditor.com
    // myLBFH.co.uk's One Page Referral System v1.0
    //
    // Instructions:
    // 1) Setup a database and then fill in the config boxes below. 
    // 2) Login and run the script with the install module 
    // ie. www.mysite.com/referrer.php?mode=install
    // If you receive a success message then hazaa! You're done.
    // Receive an error message and you may wanna check your config again.
    //
    //////////////////////
    
    // Configs:
    $db_host = "localhost";                    // Mysql Host.
    $db_login = "user_user";            // Mysql username.
    $db_pass = "pass";                    // Mysql password.
    $db_name = "user_table";                // Mysql database This can be a existing database.
    $refer = "links";                        // Table the links're kept in
    $stats = "stats";                        // Table the stat're logged in.. simple eh? DO NOT MAKE THIS THE SAME AS THE LINKS TABLE!!!
    $admin_user = "admin";                     // Admin username
    $admin_pass = "nimda";                  // Admin password
    $limt = "30";                            // List limit for referral stats
    $interstitial = "0";                    // User interstitial ads 0=False 1=True
    $inter_dela = "5";                        // Time delay before redirect (seconds)
    $inter_code = "<a href=\"http://www.mylbfh.co.uk\">MyLBFH.co.uk</a>"; // If the above is true, place your ad code here.
    // Remember to add \s before the " or $ signs to avoid errors.
    
    // Configuration set up - the rest will be done on install!
    // DO NOT EDIT BELOW THIS LINE WITHOUT BACKUPS OR PHP KNOWLEDGE
    
    //////////////////////
    //////////////////////
    //////////////////////
    
    // Check your install will work
    if($refer==$stats){
        echo "<font color=red><b>FATAL ERROR!</b> </font>Your \$refer and \$stats variables are the same! Please correct this error in config to continue loading.";
    } else {
    // Definitions
    $admin=$_POST['admin'];
    $pass=$_POST['pass'];
    $go=$_GET['go'];
    $link_url = $_POST['link_url'];
    $notes = $_POST['notes'];
    
    // Start database
    $db=0;
    openDB();
    // We want our users to be happy so we'll redirect them first, save loading it all by bunging this in an else/if
    if($go){
        // thank god for phpmyadmin eh? This loads the link_url next to that ID
        $sql = 'SELECT `link_url`, `clicks` FROM `' . $refer . '` WHERE `id` = ' . $go . ' LIMIT 0, 30 ';
        $result = mysql_query($sql);
            echo mysql_error();
        if (!$result) {
       $message  = 'Invalid query: ' . mysql_error() . "\n";
       $message .= 'Whole query: ' . $query;
    }
    while ($row = mysql_fetch_assoc($result)) {
        // add one, get stat details and retrieve the link, store counter and stats then redirect.
        $count = $row[clicks]+1;
        $ref=@$HTTP_REFERER;
        $iii=getenv(REMOTE_ADDR);
        $now = date( "Y-m-d H-i-s");
        $sql1="UPDATE `" . $refer . "` SET `clicks` = '$count' WHERE `$refer`.`id` =$go ;";
    $sql2="INSERT INTO `" . $stats . "` ( `id` , `referrer` , `date` , `ip` ) 
    VALUES (
    NULL , '" . $ref . "', '" . $now . "', '" . $iii . "'
    );";
            mysql_query($sql1);
        mysql_error();
            mysql_query($sql2);
        mysql_error();
        if($interstitial=="1"){
            // Ads
            echo $inter_code;
            
            echo "<META HTTP-EQUIV=\"REFRESH\"
          CONTENT = \"$inter_dela; URL=$row[link_url]\">";
            echo "<p><small><center><a href=\"" . $row[link_url] . "\">Redirecting...</a></small>";
            
        } else {
            // No ads
            header("Location: $row[link_url]");
        }
    }
    } else {
    // Easier for me to make by shoving the rest in this class.
    loggedin();
    }
    }
    
    // Run through the classes here. 
    
    // Loggedin(), the core of it all
    function loggedin(){
        // Find the variables
                global $refer;
                global $link_url;
                global $notes;
                global $admin_pass;
                global $admin_user;
        // I have a confession, I stole the login from a tutorial.
    session_start(); 
    $_Username = $admin_user; 
    $_Password = $admin_pass; 
    if (isset($_POST['Submit'])) { 
        if ($_POST['Username'] == $_Username && $_POST['Password'] == $_Password) { 
            $_SESSION['Logged_In'] = "True"; 
            $_SESSION['Username'] = $_Username; 
        } 
    } 
    if (!isset($_SESSION['Logged_In'])) { 
    // If the user isn't logged in, run blank() and display a login box.
       blank();
     echo '<p><form method="post" action="' . $_SERVER['PHP_SELF'] . '"> 
            Username: <input type="textbox" name="Username"><br> 
            Password: <input type="textbox" name="Password"><br> 
            <input type="Submit" name="Submit"> 
        </form><br>'; 
    
        } 
    else 
    { 
        // If the user is logged in, display the admin panel and selected module 
        // (it's not really a proper module, just easier to call it that)
        
        // Admin header
        echo "Logged in - <br>";
        echo "<center><a href=\"?mode=\">Home</a> ||<a href=\"?mode=new\">Add new link</a> || <a href=\"?mode=editlink\">Edit existing link</a> || <a href=\"?mode=stats\">View Statistics</a> ||
        <a href=\"" . $_SERVER['PHP_SELF'] . "?mode=logout\">Logout</a><br><p><p><a href=\"http://mylbfh.co.uk/\"><small>Don't forget to check the site!</small></a><p></center>";
    
        if(isset($_GET['mode'])&&$_GET['mode']=="new"){ // New links, simple text box    
            echo "<title>Admin - Add new link</title><table align=center border=1 cellspacing=0><td align=center><form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">
        Full Link: <input type=\"text\" name=\"link_url\" value=\"http://www.\"><br>
        Notes: <input type=\"text\" name=\"notes\"><br>
        <input type=\"hidden\" name=\"mode\" value=\"add\">
        <input type=\"submit\" value=\"Add link!\"></td></table>";
    } elseif(isset($_GET['mode'])&&$_GET['mode']=="logout"){ // Logout, nice and easy!
        // Logout
        session_start(); 
        $_SESSION = array(); 
        session_destroy(); 
        echo '<title>Admin - Logging out!</title><META HTTP-EQUIV="refresh" content="1; URL="' . $_SERVER['PHP_SELF'] . '">'; 
            } 
         elseif(isset($_GET['mode'])&&$_GET['mode']=="stats"){ // Load stats module, runs a loop through current stats, displays in a table.
    echo "<title>Admin - Click Stats</title>";
    global $stats;
    global $limt;
                $result=mysql_query("SELECT * 
    FROM `" . $stats . "` 
    ORDER BY `" . $stats . "`.`id` DESC LIMIT 0, " . $limt . "");
                echo mysql_error();
    
                    echo "<table border=1 width=100% cellspacing=0><tr>";
                    echo "<td><b>REFERRER</b></td><td><b>IP</b></td><td><b>DATE:TIME</b></td></tr>\r\n";
                    echo "<font size=1>";
      while ($row=mysql_fetch_array($result))
                { 
                    echo "\r\n";
                    echo "<td><a href=\"$row[referrer]\" target=\"_blank\">$row[referrer]</a></td>\r\n";
                    echo "<td>$row[ip]</td><td>$row[date]\r\n";
    echo "\n\r";
                    echo "</td></tr>";
    }         } 
         elseif(isset($_GET['mode'])&&$_GET['mode']=="install"){ // Install module - will not break if run a second time so safe to leave it here.
             echo "<title>Admin - Install</title>";
    checktable();
    } elseif(isset($_GET['mode'])&&$_GET['mode']=="editlink"){ // NEW: Edit links after install
            echo "<title>Admin - Add new link</title><table align=center border=1 cellspacing=0><td align=center><form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">
        Link ID: <input type=\"text\" name=\"ids\" value=\"\"><br>
        New link: <input type=\"text\" name=\"link_url\" value=\"\"><br>
        Notes: <input type=\"text\" name=\"notes\" value=\"\"><br>
        <input type=\"hidden\" name=\"mode\" value=\"edit_link\">
        <input type=\"submit\" value=\"Find link!\"></td></table>";
        
    } elseif(isset($_POST['link_url'])&&$_POST['mode']=="edit_link"){ // NEW: Handles link edit
    $link_url = $_POST['link_url'];
    $notes = $_POST['notes'];
    $newid = $_POST['ids'];
    
    $query="UPDATE `" . $refer . "` SET `link_url` = '" . $link_url . "',
    `notes` = '" . $notes . "' WHERE `links`.`id` =" . $newid . "";
                $result1=mysql_query("$query");
    
                          if ($result1){
                                global $succes;
                  echo "<title>Admin - Link updated successfully</title><p><font color=\"green\"><b>Link updated successfully.</b></font><p><br>";
                        }
                                else{
                                    echo "<title>Admin - Edit link failed</title><b><br><font color=red>Error: </b>";
                        echo mysql_error();
                                exit;
                                }
    
    
    } elseif(isset($_POST['link_url'])&&$_POST['mode']=="add"){ // Handles the info sent from "new" module.
    global $refer;
    $query2="INSERT INTO `" . $refer . "` ( `id` , `link_url` , `clicks` , `notes` ) 
    VALUES (
    NULL , '" . $link_url . "', '0', '" . $notes . "'
    );";
                $result1=mysql_query("$query2");
                              if ($result1){
                                global $succes;
                  echo "<title>Admin - New link added successfully</title><p><font color=\"green\"><b>New link added successfully.</b></font><p><br>";
                        }
                                else{
                                    echo "<title>Admin - New link failed</title><b><font color=red>Error: </b>";
                        echo mysql_error();
                                exit;
                                }
            } else {
            // Admin home, runs listref(), and advanced version of blank()
            listref();
    }
    } 
    }
    // List all details on links (id,url,clicks,notes), takes it all out of a database and loops through it all
    function listref(){    
        global $refer;
                    $result=mysql_query("SELECT * FROM " . $refer . "");
                echo mysql_error();
    
                    echo "<table border=1 width=100% cellspacing=0><tr>";
                    echo "<td><b>ID</b></td><td><b>URL</b></td><td><b>CLICKS</b></td><td><b>NOTES</b></td></tr>\r\n";
                    echo "<font size=1>";
      while ($row=mysql_fetch_array($result))
                { 
                    echo "<td>$row[id]</td>\r\n";
                    echo "<td><a href=\"?go=$row[id]\" target=\"_blank\">$row[link_url]</a></td>\r\n";
                    echo "<td>$row[clicks]</td><td>$row[notes]\r\n";
    echo "\n\r";
                    echo "</td></tr>";
    }
    }
    
    // Blank page (will have a login box due to the loggedin() thingy
    function blank(){    
        global $refer;
        echo "<title>Referrals</title>You have attempted to access a referral page. For you convenience, all referrals on this page are listed below:<br>";
            $result=mysql_query("SELECT * FROM " . $refer . "");
              while ($row=mysql_fetch_array($result))
                { 
        echo "<a href=\"?go=$row[id]\">$row[link_url]</a><br>";       
    }
        echo "<a href=\"http://www.mylbfh.co.uk/\">http://www.mylbfh.co.uk/</a><br>";       
    
        }
    
    
    // Check if table exists - entire install module really..
    function checktable(){
        global $db_name;
        global $refer;
        global $stats;
            $query = "USE $db_name";    
        $result=mysql_query($query);
    if (!$result){$query1="CREATE DATABASE `$db_name`";$result1=mysql_query("$query1");}
            $query2="USE $db_name";
            // Again, thank god for phpmyadmin!
            $query3="CREATE TABLE `" . $refer . "` (
    `id` int( 5 ) NOT NULL AUTO_INCREMENT ,
    `link_url` varchar( 255 ) NOT NULL default '',
    `clicks` varchar( 10 ) NOT NULL default '0',
    `notes` varchar( 255 ) NOT NULL default '',
    PRIMARY KEY ( `id` ) ,
    UNIQUE KEY `link_url` ( `link_url` ) 
    ) TYPE = MYISAM AUTO_INCREMENT =1;";
    $query4="CREATE TABLE `" . $stats . "` (
    `id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `referrer` VARCHAR( 255 ) NOT NULL ,
    `date` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
    `ip` CHAR( 15 ) NOT NULL 
    ) ENGINE = MYISAM ;";
                $result2=mysql_query("$query2");
                $result3=mysql_query("$query3");
                $result4=mysql_query("$query4");
                                          if ($result2 && $result3 && $result4){
                                global $succes;
                  echo "<font color=\"green\">Setup completed successfully.</font><p><br>";
                        }
                                else{
                        echo "<font color=Red><b>Error:</b> Either there was an error in setup or the database has already been configured:<br><ul>
                        - If this is the first time you have tried to run this script, check your mysql settings. <br>
                        - If your database details are correct, please run the following queries manually through phpmyadmin:<br>
                        <br></center>" . $query1 . "<br>" . $query2. "<br>
                        " . $query3 . "</b><center><p>
                        If you really need help, email goglgourd @ gmail . com.<br><b>SQL Error:<i> ";
                        echo mysql_error();
                                exit;
                                }
    }
    function openDB(){    
            global $db,$db_host,$db_login,$db_pass,$db_name;
            $db=mysql_connect("$db_host","$db_login","$db_pass");
            mysql_select_db("$db_name",$db);
    }
    
    
    // Optional credits, remove the "//" on the two lines below to show your love.
    // <p><small>Powered by
    // <a href="http://www.mylbfh.co.uk"/>GoglGourd</a></small>
    
    //////////////////////
    //    This program is free software; you can redistribute it and/or modify
    //    it under the terms of the GNU General Public License as published by
    //    the Free Software Foundation; either version 2 of the License, or
    //    (at your option) any later version.
    //
    //    This program is distributed in the hope that it will be useful,
    //    but WITHOUT ANY WARRANTY; without even the implied warranty of
    //    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    //    GNU General Public License for more details.
    //
    //    You should have received a copy of the GNU General Public License
    //    along with this program; if not, write to the Free Software
    //    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    //////////////////////
    ?>
    PHP:
    full referral system i've just finished, tis a first attempt but it works well enough :) does what you ask for and, optionally, more.
    Feature list:mylbfh.co.uk/download.php
     
    GoglGourd, Oct 6, 2006 IP
  11. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #11
    thanks GoglGourd really appriciated. but i dont know databases. Ill get someone to help me with it tho.

    2 codes are saved.


    YAY for fourm help
     
    Dirty-Rockstar, Oct 6, 2006 IP
  12. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #12
    So you OK with my code now Rockstar? Or do you need more help?

    Lee.
     
    BRUm, Oct 7, 2006 IP
  13. Dirty-Rockstar

    Dirty-Rockstar Guest

    Messages:
    252
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #13
    lets say im ok for now. I have a friend helping me with the code.

    really appriciated
     
    Dirty-Rockstar, Oct 7, 2006 IP