BigToach.com

PHP Snippets

link_track

Information

(PHP Version >= 4.3.0)
Functions used in this snippet: file_exists, is_readable, is_writable, unserialize, file_get_contents, is_array, array_key_exists, isset, fopen, fwrite, serialize, fclose.

Description

mixed link_track( [ int id]] )

Keeps track of the number of times that clients have clicked a link. To find the number of clicks that a link has, leave id blank. To update a certain link, set id to the id of the link that you want to update.

Snippet

<?php
function link_track($id=NULL){
    
$file 'somefile.txt'// this is the file stuff is stored in
// make sure php can read and write to this file
    
if(!file_exists($file) || !is_readable($file) || !is_writable($file)){
        return;
    }
    
$links = array(0=>'http://www.bigtoach.com'1=>'http://www.neverside.com'2=>'http://www.google.com'); // change these to your links
    
$array unserialize(file_get_contents($file));
    
$array is_array($array) ? $array : array();
    if(
$id !== NULL){
        if(!
array_key_exists($id$links)){
            return 
'sorry there is no link to the id ' $id;
        }
        
$array[$id] = isset($array[$id]) ? $array[$id] + 1;
        
$fp fopen($file'w');
        
fwrite($fp,  serialize($array));
        
fclose($fp);
        return 
$links[$id];
    }
    
$ret = array();
    foreach(
$links as $key=>$value){
        
$ret[$key]['site'] = $value;
        
$ret[$key]['clicks'] = isset($array[$key]) ? $array[$key] : 0;
        
$ret[$key]['id'] = $key;
    }
    return 
$ret;
}
?>

Example

link_track Can be used in the following way:

<?php
// this snippet is to find # of clicks
$array link_track(); // gets the array

foreach($array as $key=>$value){
    echo 
'<a href="pass.php?id=' $value['id'] . '">' $value['site'] . ' (' $value['clicks'] . ' Clicks)</a><br />';
}
// you can also get click counts like this

echo '<a href="pass.php?id=0">http://www.bigtoach.com (' $array[0]['clicks'] . ' Clicks)</a>';

// pass.php would look as the following
$_GET['id'] = isset($_GET['id']) ? intval($_GET['id']) : NULL;
$redirect link_track($_GET['id']);
if(
strstr($redirect'http')){
    
header('Location: ' $redirect);
}else{
    echo 
'Sorry that link does not exist';
}
?>

Added on Aug 18th at 6 pm by Scott - 0 Comments
Updated on Aug 18th at 6 pm.


0 Responses to link_track

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: