Search code examples
javascriptphponclickfile-get-contentsfile-put-contents

how to pass number of hits count based on button action in php


We are developing web sit. We have button.In button action we placed PDF file downloading.Working fine.But We need How do I count download my PDF file from my website.

We tried like this but We not get.

<?php
//$Down=$_GET['Down'];
$a="hello";
$i=0;
?>
<script type="text/javascript">
    var i=0;
    function submitForm()
    {
        <?php
        $i = @file_get_contents('count.txt'); // read the hit count from file
        echo $i; //  display the hit count
        $i++; // increment the hit count by 1
        @file_put_contents('count.txt', $i); // store the new hit count
        ?>  
    }
</script>
<html>
<head>
</head>

<body>
    <input type="button" onclick="submitForm()" value="submit 1" />
</body>
</html>

We got nothing .We are new to PHP Please guide to us.


Solution

  • Well, you can download you PDF and count at form submit:

    <?php
    $i=0;
    $i = (int) @file_get_contents('count.txt'); // read the hit count from file
    if(!empty($_POST)) {
        $i++; // increment the hit count by 1
        @file_put_contents('count.txt', $i); // store the new hit count
        // Download
        $file = 'filename.pdf';
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
    }
    

    Now use echo $i; where you want to display the number of downloads.

    In html the form should be:

    <form method="post" action="">
        <input type="submit" name="download" value="Download">
    </form>