Click counter when link is clicked PHP/JS - javascript

I have a little script here that counts clicks when link is clicked and stores it in .txt file, but it works fine when I have only "click=yes" under href. But I can't make it to track clicks when I have link to external site.
Here is my code:
<?php
if(!file_exists('counter.txt')){
file_put_contents('counter.txt', '0');
}
if($_GET['click'] == 'yes'){
file_put_contents('counter.txt', ((int) file_get_contents('counter.txt')) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>counter example</title>
</head>
<body>
<h1><?php echo file_get_contents('counter.txt'); ?></h1>
clickMe
</body>
</html>
My guess is it has to do something with header('Location: ' . $_SERVER['SCRIPT_NAME']); but I can't figure it out so I could really use some help.
And is it somehow possible to have multiple links save to the same file, and when I show it on website it's sorted from largest number to smallest? I have an idea how to do it with MySQL database but I can't use it at place where this will be implemented.
Thanks in advance!
Cheers!

Your server never sees the URI being accessed as the client leaves your page. To do something like this, it may be best to set up a redirect which works like this
click me
(Make sure the external site's URL is URL encoded as you're passing it as a GET component of a URL to your own page)
Then in goto.php you store your click and send a redirect header
if(!file_exists('counter.txt')){
file_put_contents('counter.txt', '0');
}
file_put_contents('counter.txt', ((int) file_get_contents('counter.txt')) + 1);
header('Location: ' . $_GET['href']);
Now you can track these clicks, you can add your domain-specific counters in goto.php instead of your text file

You could use Javascript to catch click on a link , send data via AJAX call. Here is small sample using JQuery.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(
function() {
$('a').click(linkClicked);
}
);
//this funciton will be called on every click on any link on page
function linkClicked() {
var url = $(this).attr('href');
//call PHP script to save URL ./saveurlclicks.php?url=CLICKEDURL
$.get('./saveurlclicks.php', {'url': url})
//be sure to return true so user can navigate further
return true;
}
</script>
</head>
<body>
<a href='/some href' >asasa</a>
<a href="www.google.com" >google</a>
</body>
</html>
<?php
//saveurlclicks.php
// here we save links in file but using serialized array
// if you need to get count of links clicked ,
// have a second script that unserializes array and sort it in revers order
$url = #$_GET['url'];
$counterFile = 'counter.ser';
if ($url) {
if(file_exist($filename))
$links = unserialize(file_get_contents($filename));
else $links=array();
if (!isset($links[$url])) {
$links[$url] = 0;
}
$links[$url] ++;
file_put_contents($counterFile, serialize($links));
}

I love the simple solution by Paul S., but if you want to track the clicks with date, you can do something like this:
03/03/2022 14
04/03/2022 2
<?php
$dateexists = false;
if(!file_exists('counter.txt'))
{ $fh = fopen('counter.txt', 'w');
fclose($fh); }
$datecounts = file('counter.txt', FILE_IGNORE_NEW_LINES);
foreach($datecounts as $key => $datecount){
list($date, $count) = explode("\t", $datecount);
$count = (int) $count;
if($date == date('d/m/Y'))
{ $datecounts[$key] = $date."\t".++$count;
$dateexists = true; }
}
if(!$dateexists)
{ $datecounts[] = date('d/m/Y')."\t1"; }
$fh = fopen('counter.txt', 'w');
if (flock($fh, LOCK_EX)) {
foreach($datecounts as $datecount)
{ fwrite($fh, $datecount.PHP_EOL); }
flock($fh, LOCK_UN);
}
else
{ //couldn't lock, might want to do stuff here }
fclose($fh);
header('Location: ' . $_GET['href']); // the redirect
?>

Related

Is the function binded to the button always executed or did I make a mistake?

So I have this PHP page, with at the start some unimportant stuff and a session opening :
<?php
session_start();
?>
I want the disconnect button to appear only if the user is already connected, which means that $_SESSION['Pseudo'] is set. If this is the case, I create a button, and bind to that button a function to destroy the session. The problem is, each time I go on this page, the session is destroy, even though it's in a condition.
Here's my code :
<?php
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
<?php
session_destroy();
?>
window.location.href = "/"
}
}
</script>
Any clue ?
You cannot combine PHP within Javascript like that.
When you're doing , it's not a part of the Javascript. It's PHP code and is executed as part of the PHP code in the file.
This means that it has nothing to do with the javascript aspect. your updateBtn function is effectively, when the page source code loads:
function updateBtn() { window.location.href = "/" }
What you really want to do is make it so that when someone clicks the button, it takes them to a logout page or a page with a logout query param.
eg.
<?php
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
session_destroy();
echo 'You have successfully logged out!';
}
if (isset($_SESSION["pseudo"])) {
echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
let btn = document.getElementById('deco');
if (btn) {
btn.addEventListener('click', updateBtn);
function updateBtn() {
window.location.href = "/?action=logout"
}
}
</script>

Send data over to another html file

I am trying to get certain data from my database on my (1) HTML page and display it on the (2) HTML page.
My codes for (1) html file:
<html>
<head>
<script src="example.js"></script>
</head>
<body>
.
.
.
<button item="' + count + '" onclick="getData(this)">Example</button>
.
.
.
</body>
</html>
And the JS for it:
.
.
.
var currentIndex = 0;
//This function is to display the details of an individual item
function getData(element) {
var request = new XMLHttpRequest();
request.open("GET", "/theroute", true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function () {
var example = JSON.parse(request.responseText);
var item = element.getAttribute("item");
currentIndex = item;
document.getElementById("data1").textContent = example[item].name;
document.getElementById("data2").src = example[item].age;
}
request.send();
}
.
.
.
I want to get these data in my (2) HTML page (for example):
<html>
<head>
<script src="example.js"></script>
</head>
<body>
<h4 id="data1"></h4>
<h4 id="data2"></h4>
</body>
</html>
I saw this Get data from one html file and display it using another html file, but I'm not sure how to use this for my case here.
Sorry, I am new to this, so giving a detailed explanation for your solution would be very helpful. I am using vanilla JS only so please no jQuery. Any help would be appreciated
I hope this might prove of use to you. The button(s) have had the custom item attribute replaced with the dataset equivalent to ensure the html is valid. Normally I'd suggest also using external event handlers rather than adding onclick=getdata() to the elements inline but for brevity here they remain.The function, when invoked by clicking a button, will construct the relevant querystring to send to the endpoint ( for you it would be /theroute?id=X&name=Y&age=Z etc ) which queries the database and sends the response back. The response is used to generate the menu of hyperlinks which take the user to page 2 when clicked. I think this is what you were trying to explain. You could copy the entire code and create a new page to see in action.
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['item'] ) ){
ob_clean();
/*
emulate "/theroute" and send some data back to the ajax callback.
This data would really be fetched from the database but below is
simply randomly generated data for display/test purposes.
*/
$payload=[];
$item=$_GET['item'];
for( $i=0; $i < 10; $i++ ){
$payload[]=[
'id' => $i,
'name' => 'Geronimo '.uniqid().' '.$item,
'age' => mt_rand(16,80)
];
}
exit( json_encode( $payload ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
function getData( e ) {
var xhr = new XMLHttpRequest();
var ul=document.getElementById('menu');
/* The above PHP code is to emulate the real endpoint /theroute */
xhr.open( "GET", location.href +'?task=fetch&item='+e.target.dataset.item, true );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = function() {
var json = JSON.parse( xhr.response );
json.forEach(obj=>{
var id=obj.id;
var name=obj.name;
var age=obj.age;
var li=document.createElement('li');
li.appendChild( createhyperlink(id,name,age) );
ul.appendChild( li );
});
}
xhr.send();
}
function createhyperlink(id,name,age){
var a=document.createElement('a');
a.href='page2.html?id='+id+'&name='+name+'&age='+age;
a.innerHTML='View '+name;
return a;
}
</script>
</head>
<body>
<ul id='menu'></ul>
<?php
for( $i=1; $i <=10; $i++ ){
echo "<button data-item='{$i}' onclick='getData(event)'>Example #{$i}</button>";
}
?>
</body>
</html>

HTML Form Text to Speech speaks the file name and PHP, Doubles Form

I am working on a webpage that takes HTML form input, processes it on a loop using PHP, then displays the PHP echo output in a div using jQuery, then TTS speaks a message using ResponsiveVoiceJS.
The problem that is visible right now is that, upon loading of the page, the TTS starts speaking the webpage file name and some random PHP on a loop, then displays the form twice.
It shouldn't do any of that!
Since I am not sure which part of the code is causing the issue, here is the code in its entirety:
<html>
<head>
</head>
<body>
<form action="<?php
echo $_SERVER['PHP_SELF'];
?>" method="post">
What is your URL? <input type="text" name="pastedurl"><br>
What is your minimum interval? <input type="text" name="interval"><br>
<input type ="submit">
</form>
<?php
set_time_limit(18000);
if (isset($_POST['submit']))
{
// echo "stopped here";
// die; //THIS DOESN'T WORK EITHER
$pastedlink = $_POST['pastedurl'];
$pastedlink2 = $_POST['pastedurl'];
$rate = $_POST['interval'];
parse_url($_POST['pastedurl'], PHP_URL_HOST);
if (parse_url($_POST['pastedurl'], PHP_URL_HOST) == 'www.instructables.com')
{
for ($z = 0; $z < 2880; $z++)
{
$tutorial_json = file_get_contents($pastedlink);
$tutorial_array = json_decode($tutorial_json, true);
$oldviews = $tutorial_array['views'];
sleep(30);
$tutorial_json2 = file_get_contents($pastedlink);
$tutorial_array2 = json_decode($tutorial_json2, true);
$currentviews = $tutorial_array2['views'];
$viewcount1 = (int) $oldviews;
$viewcount2 = (int) $currentviews;
$change = $viewcount2;
$change -= $viewcount1;
$rateasint = (int) $rate;
if ($change >= $rateasint)
{
$sayit = "Alert! Your Tutorial has gained " . $change . " more views";
echo $sayit;
}
}
}
else
{
exit("Error: URL submitted was not from www.instructables.com");
}
}
?>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(document).ready(function(readyEvent) {
speakInnerHTML();
});
function speakInnerHTML() {
var speek = document.getElementById("load_updates");
responsiveVoice.speak(speek.innerHTML);
}
</script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_updates').load('<?php
echo $_SERVER['PHP_SELF'];
?>',speakInnerHTML).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<div id="load_updates"> </div>
</body>
</html>
Sorry about the poor formatting, I am a noob and don't know the methods of formatting these programming languages!
Here is a video of the error in action:
youtube
1.
die; //THIS DOESN'T WORK EITHER
die() is a function, and despite the wonders of echo, all functions are called with parentheses.
2.
isset($_POST['submit'])
This doesn't work because there are variables with the name submit.
To fix that, add the name attribute to your submit control, like this:
<input type="submit" name="submit">
3. You are loading the page itself with jQuery, even though it contains... well... itself. It's going to recursively fill the page with its own instances every 10000ms. And every one of that instance is going to do that too. You need to query the page with the data from the form, not just load it. And add a conditional so that if there is $_POST data, the page does not display all the HTML.

Java Script for page redirecting over PHP SESSION status

I m trying to redirect pages according to PHP session status, so that, if session start () redirect to page1 else page 2
but seems like i kinda didn't done well with coding.
code goes as:
<script>
if (session_start();) {
window.location = 'page1.php';
}
else {
window.location = 'page2.php';
}
</script>
Any Help is Appreciated..
I think u want something like this:
<script>
<?php
session_start();
if($_SESSION['login'] == true) {
$_SESSION['login'] = false;
echo "window.location = 'page1.php';";
} else {
$_SESSION['login'] = true;
echo "window.location = 'page2.php';";
}
?>
</script>
First of all, session_start is a php-related function, and you are using it inside javascript.
You should prepend and append to every PHP code you want to use both these symbols:
<?php # Start
?> # End
Second Point: If you need to redirect someone to some page, use header("location") in PHP.
So your result code should be:
<?php
if(session_start()){
header("location: page1.php");
}
else{
header("location: page2.php");
}
?>
Btw.. I don't understand why you are using a "session_start" as a condition.
// create a php file first
index.php
// include js on all pages
// create a javascript file
func.js
<script type="text/javascript">
// lets create a function
function newtab(page)
{
if(page != "")
{
window.open(page,"_self","location=yes");
}
}
</script>
<?php
// no harm, we can still add javascript here
// we assume this is index.php
// start a session here
session_start();
// you need to create a switch
if(!isset($_SESSION['switch']))
{
echo '<script>newtab("page1.php")</script>';
}
else
{
echo '<script>newtab("page2.php")</script>';
}
// you can play with the switches
?>
hope this helps
Just do it with PHP:
if(session_start()){
header("Location:page1.php"); die();
} else {
header("Location:page1.php"); die();
}

Dynamic page update by AJAX

I've got a problem.
I'm using AJAX to load pages and it works correctly, but I can't escape a bug.
When I load page, first time it works correctly but then I go to another page, AJAX loads the page I want, but it has double tags like <head> and <footer>.
I mean when I load page a second time, the page loads the same page in <div>.
It's like picture in picture.
I use in templates code like this:
<?php echo $header ?>
My content
<?php echo $footer ?>
And every page load the same code after I get back to previous page by link.
My ajax code:
function showContent(link) {
var cont = document.getElementById('content');
var loading = document.getElementById('loading');
window.history.replaceState('', 'Title', link);
cont.innerHTML = loading.innerHTML;
var http = createRequestObject(); // создаем ajax-объект
if( http ) {
http.open('get', link); // инициируем загрузку страницы
http.onreadystatechange = function () { // назначаем асинхронный обработчик события
if(http.readyState == 4) {
cont.innerHTML = http.responseText; // присваиваем содержимое
}
}
http.send(null);
} else {
document.location = link; // если ajax-объект не удается создать, просто перенаправляем на адрес
}
}
// создание ajax объекта
function createRequestObject() {
try { return new XMLHttpRequest() }
catch(e) {
try { return new ActiveXObject('Msxml2.XMLHTTP') }
catch(e) {
try { return new ActiveXObject('Microsoft.XMLHTTP') }
catch(e) { return null; }
}
}
}
What Can I do?
Because if I delete Tags header and footer my page doesn't have design at all.
And as u see, I change URL (important for me).
I need solution which will help me load templates without double-tagging.
In your template, be sure that you have something like
<?php echo $header ?>
<div id="content">My content</div>
<?php echo $footer ?>
And that id="content" is unique, only there and not in your $header or $footer.
This can happen if you are not clearing the previous content and the new content is being "appended" to the existing DOM.
So following points could be your solution.
In each ajax call, before updating the container element, clear the existing element, eg. cont.innerHTML = '';
Remember to keep track of any event bindings that are coming with the incoming response.
Move this line var cont = document.getElementById('content'); inside the ajax call.
If the pages you're pulling in with the JavaScript XHR (Ajax) also contain the PHP header and footer code, then you'll need to replace those also with your XHR:
<div id="content">
<?php echo $header ?>
My content
<?php echo $footer ?>
</div>
Wrap your content div tag around the header and footer in order to overwrite them rather than duplicate them.
Alternatively, the way I've implemented a PHP template system is like this:
index.php
<?php
// GET PAGE
if ( isset($_GET['page'])
&& '' != $_GET['page']
&& !preg_match('!^(/|\.|(ht|f)tp://)!', $_GET['page'])
) $page = $_GET['page'];
else $page = 'home.html';
// EXECUTE TEMPLATE
require('template.php');
?>
template.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<!-- plain HTML header goes here -->
<!-- RETRIEVE PAGE -->
<?php require('pages/' . $page); ?>
<!-- plain HTML footer goes here -->
</body>
</html>
samplepage.html
<h2>Sample Page Header</h2>
<p>Sample page content goes here.</p>
phppage.php
<h2>PHP Page Header</h2>
<p><?php echo 'PHP page content goes here.'; ?></p>
Everything goes to the index.php file. You can use PHP to block direct access to page files, or if using Apache web server you can use .htaccess to redirect all requests to the index.php file.
The technical URL looks like http://example.net/index.php?page=samplepage.html. But, using .htaccess can be effectively converted to http://example.net/samplepage.html with:
RewriteRule ^(.*)$ index.php?page=$1&%{QUERY_STRING} [L]

Categories