Neoseeker : Blogs : Benedict : Tags : javascript

Benneh's blog

PHP count number of times link has been clicked

    This script is for Monferno, as he requested it, but I thought I would share it with other people so the google crawlbots can get at it.


    To use this, create two pages and one file: The php page with the link on, (I use count.php) and the php page that is linked to (I use count2.php), and a blank text file in the same directory (I use 1.txt).

    First, in the page that is being linked to (count2.php) put this code at the top of the body:
    code
    <?php
    error_reporting(0); #Removes Notices that appear with this code
    $count_my_page = ("1.txt");
    $hits = file($count_my_page);
    $hits[0] ++;
    $fp = fopen($count_my_page , "w");
    fputs($fp , "$hits[0]");
    fclose($fp);
    ?>
    


    That will write one number onto the file (1.txt) which can be echoed later on the other page.

    Now, on your page with the links put this in the head (Count.php):
    code
    <script language="javascript">
    function toggle() {
    var linkname = "Link Name" // CHANGE THIS TO THE LINK NAME YOU PUT IN THE A TAG!!!!
    var ele = document.getElementById("toggleText");
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
    ele.style.display = "none";
    text.innerHTML = linkname;
    }
    else {
    ele.style.display = "block";
    text.innerHTML = linkname;
    }
    }
    </script>
    

    Making sure you change the var linkname to something (Keep the quotes).

    In the body, put this:

    code
    <div><a href="count2.php" onmouseover="java
    script:toggle();" onmouseout="javascript:toggle();" id="displayText">Link Name</a><br />
    <div id="toggleText" style="display: none;">
    <?php
     $myFile = "1.txt";
     $fh = fopen($myFile, 'r');
     $theData = fread($fh, 5);
     fclose($fh);
     echo $theData;
    ?>
    </div></div>
    

    Important note: Remove the line break between "java" and "script" in the above. I had to do that so the conversion works in code tags.
    Replace "count2.php" with the link to the page with the other php on.
    Replace Link Name with the link name you put in the JS code above.

    And you are done! Any questions/problems put them in the comments below. I'll eventually upload the three files here so that you can see them or troubleshooting. THIS CODE HAS ONLY BEEN TESTED ON FIREFOX. You will need a server (wampapache I use) to test this code. If you put the link to open in a new window, it will not automaticaly update until you page refresh.

read more..
(0.0731/d/aeon)