Your open source for Development and Design

Tracking visitors with PHP and Predefined variables

Filed under: Apache,PHP — Tags: , , , — Adi @ 4:37 pm January 15, 2009

Although Google analytics can tell us a lot about who is visiting our websites it is still flawed in many ways. Google analytics is a powerful tool but if the user has disabled Javascript or you want to know live stats it can be pretty useless.

Developing our own can be much more versatile as we can gather information straight from the server using PHP’s Predefined variables.

You can add your own version of with a database and a few lines of PHP code.

$time = mktime();
if (isset($_SERVER['REQUEST_METHOD'])) {   // HTTP-method
   $method = $_SERVER['REQUEST_METHOD'];
} else {
   $method = "";
}
if (isset($_SERVER['REMOTE_ADDR'])) {      // IP-adress
   $ip_adress = $_SERVER['REMOTE_ADDR'];
} else {
   $ip_adress = "";
}
if (isset($_SERVER['HTTP_USER_AGENT'])) {  // Browser
   $browser = $_SERVER['HTTP_USER_AGENT'];
} else {
   $browser = "";
}
if (isset($_SERVER['PHP_SELF'])) {         // Current page
   $page = $_SERVER['PHP_SELF'];
} else {
   $page = "";
}
if (isset($_SERVER['HTTP_REFERER'])) {    // Previous page
   $referer = $_SERVER['HTTP_REFERER'];
} else {
   $referer = "";
}

$sql="INSERT INTO user_log (time, method, page, referer, adress, browser) // Insert into database as new row
					VALUES('$time','$method','$page','$referer','$ip_adress','$browser')";
mysql_query($sql);

PHP foreach loop through post request

Filed under: PHP — Tags: , , , , — Adi @ 3:48 pm January 14, 2009

I use a variation of this code on most websites I have coded as it is versitile and full of uses when working with dynamic content. An example might be reusing the same mail() function for differant forms, you could loop through what is posted to it and print it out in the body of the mail.

The foreach loop will process each of the requests set to the page. The $_REQUEST can be changed to just $_POST to check only posted form data or any other type of request.

The following loop contains a few examples of what you could do with the request once you have it.

foreach ($_REQUEST as $key => $value)
{
$value = mysql_real_escape_string( $value );
$value = addslashes($value);
$value = strip_tags($value);
if($value != ""){$requestnumber ++;}
echo $key. ' - '.$value.'</br>';
}

« Newer Posts

Switch to our mobile site