wazy
wazy

Reputation: 1065

How to check if a link has been clicked in php

Well I am new to this so I want to record when the user clicks on the link that php prints and query a mysql database. I know how to query the database using php already but I'm not sure if it is possible to know if the user clicked on the link.

I printed a link like so.

print ('<a id="myLink" href="http://www.google.com" target="_blank">google</a>');

Upvotes: 1

Views: 12152

Answers (4)

John
John

Reputation: 529

To track the link, you'd need to create a link tracking script on your server. i.e. linktracker.php

Then, change your code to point the link to that script, passing the forwarding url i.e

<a id="myLink" href="http://mysite.com/linktracker.php?url=http://www.google.com" target="_blank">google</a>

In linktracker.php, you would need something like:

<?php 
    $url = $_GET['url'];
    // update your database click count for the url
    //  i.e UPDATE linkclicks SET clickcount = clickcount + 1 WHERE url = '$url'

    // forward the user to the end location
    header("Location: $url"); 

Upvotes: 5

John Green
John Green

Reputation: 13435

You need to build a URL redirection mechanism.

$link = 'http://www.google.com';
echo '<a href="/redir.php?target="'.encodeUriComponent($link).'>google</a>';

then make a redir.php:

<?php
$targetUrl = $_REQUEST['target'];
// log this targetUrl to your MySQL database.

header( 'Location:'.$targetUrl);

I absolutely wouldn't do this in JavaScript if you want to try to track links shares or something of that nature.

Upvotes: 3

Yaron U.
Yaron U.

Reputation: 7881

add onclick="handleClick()" and write javascript function named handleClick to report the click to the server uaing ajax

Upvotes: 2

IsisCode
IsisCode

Reputation: 2490

Unless the link is to your own site, you'll need to use a client-side scripting language such as JavaScript (could utilise jQuery too) to send the user's click event back to the server.

Upvotes: 1

Related Questions