skip to Main Content

I need to create a counter for a website. Every time the visitor Number Increasing when the page load and save this counter on server. In stackoverflow, I have searched many answer with this regard.

I want to Answer the full work around, for later use, who wants to know.

2

Answers


  1. Chosen as BEST ANSWER

    I have searched many answer, and at last I have appended those in this procedure :

    1. I have to store the visitor count in a file in server.
    2. On the first run, check the file if exist. If not exist create the file.
    3. Store the visitor value on that file.

    JavaScript Part :

    <script type = "text/javascript">
    
    
    function createCounterFileIfNotExist() {
        
        if(!UrlOrFileExists("https://urlForTheTextFile/text_file.txt")){
            
            var newInt = "1"; 
            document.getElementById("demo").innerHTML = newInt; 
         
            writeDoc(newInt); 
        }else{
            loadDoc(); 
        }
    }
    
    function UrlOrFileExists(url)
    {
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
          var http=new XMLHttpRequest();
        } 
        else {
          var http=new ActiveXObject("Microsoft.XMLHTTP");
        }
    
        http.open('HEAD', url, false);
        http.send();
        return http.status!=404;
    }
    
    function loadDoc() {
        var newStr = ""; 
      var xhttp = new XMLHttpRequest();
      
      if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
     xhttp=new XMLHttpRequest();
     }
    else
      {// code for IE6, IE5
      xhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      
      xhttp.onreadystatechange = function() {
          
        //   alert(this.readyState); 
        //   alert(this.status); 
          
          
          
          
        if (this.readyState == 4 && this.status == 200) {
        newStr =  this.responseText;
        
        // alert(newStr); 
        var oldInt ="1";
        var newInt; 
        
        if(newStr){
          oldInt = parseInt(newStr); 
          newInt = oldInt + 1; 
        }else{
            newInt =1; 
        }
        
         
         
         
        //   alert(newInt); 
         document.getElementById("demo").innerHTML = newInt; 
         
         writeDoc(newInt); 
        }
      };
      xhttp.open("GET", "text_file.txt", true);
      xhttp.send();
      
      return newStr; 
    }
    
    
    function writeDoc(newCounter) {
    var xmlhttp;
    if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();
     }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
            // alert('As Salamu Alaikum, Jajakumullah for Visiting Our Page.')
     }
    }
    
    xmlhttp.open("POST","phpwrite2.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("name="+newCounter);
    
    }
    
    
    </script>
    

    PHP part : (phpwrite2.php)

    <?php
    $myFile = "text_file.txt";
    
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = $_POST["name"];
    fwrite($fh, $stringData);
    fclose($fh);
    ?>
    

    Html Part :

    <div>Website visit counter:</div>
    <div id="demo" class="website-counter"> </div>
        
    <!--this script will run when the page is loaded : window.onload -->
    <script> 
            window.onload = function exampleFunction() { 
                createCounterFileIfNotExist(); 
            } 
    </script> 
    

    CSS part :

    /* Styles for website counter container */
    .website-counter {
      background-color: #ff4957;
      height: 50px;
      width: 80px;
      color: white;
      border-radius: 30px;
      font-weight: 700;
      font-size: 25px;
      margin-top: 10px;
    }
    .demo {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
       margin: auto;
        width: 50%;
     
      padding: 10px;
    }
    

  2. I’d just have a very short piece of PHP code that gets called:

    <?php
    require_once("db_connection.php");
    
    $sql = "update sitecount set count=count+1 where id=1";
    $db->query($sql);
    $exc = $db->query("select count from sitecount where id=1";
    $row = $exc->fetch();
    echo $row['count'];
    

    All your Javascript needs to do is to call the above PHP code, and the count will be returned. The id column is just because there needs to be some sort of row identifier – if you want to store distinct counts you could use that column to differentiate between them. No need to have the client try to check if a file exists on the server, no back-and-forth allowing multiple users to try to run the code at the same time, much less complicated.

    But, aren’t visit counters a bit out of fashion these days?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search