Jump to content

need help in changing perl to php


superkingkong

Recommended Posts

hi,

 

previously i'm using this perl script, but recently, i'm converting my old html website to php, so, my perl is not working with php anymore.

 

this script is to log visitors info, browser, ip and hostname.

i'm stuck with these steps, preventing the script from logging the info when user is refresing the browser.

 

appreciate if anyone can help me out with porting this perl code to php..

if (-e "$hostfile")
{
open(HOST,"$hostfile");
$hostline = <HOST>;
chop($hostline) if $hostline =~ /\n$/;
close(HOST);
($old_time,$old_number,$old_page,$old_browser) = split(/\¦/,$hostline);
}

# save host and time info and check if this is a page reload
open(HOST,">$hostfile");
$seconds = time;
print HOST "$seconds\¦$ENV{REMOTE_ADDR}\¦$ENV{'DOCUMENT_URI'}\¦$ENV{'HTTP_USER_AGENT'}";
close(HOST);

if ($time - $old_time < $interval && $ENV{REMOTE_ADDR} eq $old_number && $ENV{'DOCUMENT_URI'} eq $old_page && $ENV{'HTTP_USER_AGENT'} eq $old_browser)
{
don't do anything
} else {
process it
} 

 

appreciate if anyone could help me out with this, thanks.

Link to comment
Share on other sites

1) To prevent counting when a user refreshes the page, use sessions.  You can set a session variable to check if they have already hit that page or whatever you're trying to do.  Most of what you're trying to do in perl is similar to PHP.

 

session_start();
$_SESSION['stats'] = (isset($_SESSION['stats'])) ? $_SESSION['stats']+1 : 1;

if($_SESSION['stats'] > 1)
{
   //they refreshed the page or came back here
} else {
   //it's their first time here; your code here
}

 

2) You can use something like this (from the manual www.php.net) to check what browser they're using:

 

function get_user_browser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = '';
    if(preg_match('/MSIE/i',$u_agent))
    {
        $ub = "ie";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $ub = "firefox";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $ub = "safari";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $ub = "chrome";
    }
    elseif(preg_match('/Flock/i',$u_agent))
    {
        $ub = "flock";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $ub = "opera";
    }
   
    return $ub;
}
?>

 

3) For the IP, you can use:

 

$_SERVER['REMOTE_ADDR'];

 

4) For the host name you can use:

 

$_SERVER['REMOTE_HOST'];

 

It looks like you're storing this information in a file, so you're going to want to look at the file input/output methods from the manual. The majority of what you need for user statistics you can find here, in the manual..  Hope this helps!

 

Link to comment
Share on other sites

hi,

 

thanks a lot for the info.

 

i've managed to come out with this code:

 

what's your opinion? :P

 

<?php
session_start();

// Getting the information
$ipaddress = $_SERVER['REMOTE_ADDR'];
$page = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$page .= if(!empty($_SERVER['QUERY_STRING']), "?{$_SERVER['QUERY_STRING']}", "");
$referrer = $_SERVER['HTTP_REFERER'];
$datetime = date('D, M j, Y (T) \a\t h:i:s A');
$useragent = $_SERVER['HTTP_USER_AGENT'];
$remotehost = @getHostByAddr($ipaddress);

// Create log line
$logline = $ipaddress . '|' . $referrer . '|' . $datetime . '|' . $useragent . '|' . $remotehost . '|' . $page . "\n";

// Write to log file:
$logfile = 'log.db';

$_SESSION['stats'] = (isset($_SESSION['stats'])) ? $_SESSION['stats']+1 : 1;

if($_SESSION['stats'] > 1)
{
   //they refreshed the page or came back here
} else {
   //it's their first time here; your code here
if (!$handle = fopen($logfile, 'r+')) {
	die("Failed to open log file");
}

file_put_contents($logfile, $logline . file_get_contents($logfile));

fclose($handle);
}

?>

 

and i call it from other pages

 

<?php include ("log.php"); ?>

 

appreciate your feedback :)

Link to comment
Share on other sites

Looks good.  I just tested it on my local host and everything seems to be working/writing properly.  Nice job  ;)

 

By the way, why are you writing to a log file rather than a database?

 

 

Link to comment
Share on other sites

hi,

 

i've tried the code above, the script still logs when i refresh the browser. i'm using firefox.

 

appreciate if you can please help, thanks.

 

about the db, that will be my next step. last time my perl writes to a plain text file, since i've just converted to php, i want to make this script works first, then i'll move on to database :P

Link to comment
Share on other sites

i've tried the code above, the script still logs when i refresh the browser. i'm using firefox.

 

I'm using FF3 as well.  I refreshed the page and it doesn't write a dupe to the log.  I also made 2 separate files and included the one in the second file to ensure I had the same setup as you and it still works...

 

You don't use session_destroy(); anywhere do you?  Cause that will reset the session variable and count a page refresh.

Link to comment
Share on other sites

hi,

 

i've created a blank file with the code include ("log.php")

 

http://premium.sfdns.net/~superkin/i.php

 

everytime when i refresh that page, i get new log

 

http://premium.sfdns.net/~superkin/logv.php

this script is to view the log

 

i've tried using IE7 and ff3.. still the same :P can you please try the url above and look at the log and see whether it increments.... thanks

Link to comment
Share on other sites

yes... this is the entire script. here is the code on the pages

 

additional info: my web hosting company is using suphp 5. does that matter? it doesn't support virtual(), that's why i'm converting my perl to php

 

this is the i.php

 

<?php
echo "<br />test log script<br />";
// phpinfo ();
include ('log.php');

?>

 

this is the log.php

<?php
session_start();

// Getting the information
$ipaddress = $_SERVER['REMOTE_ADDR'];
$page = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// $page .= iif(!empty($_SERVER['QUERY_STRING']), "?{$_SERVER['QUERY_STRING']}", "");
$referrer = $_SERVER['HTTP_REFERER'];
$datetime = date('D, M j, Y (T) \a\t h:i:s A');
$useragent = $_SERVER['HTTP_USER_AGENT'];
$remotehost = @getHostByAddr($ipaddress);

// Create log line
$logline = $ipaddress . '|' . $referrer . '|' . $datetime . '|' . $useragent . '|' . $remotehost . '|' . $page . "\n";

// Write to log file:
$logfile = 'log.db';

$_SESSION['stats'] = (isset($_SESSION['stats'])) ? $_SESSION['stats']+1 : 1;

if($_SESSION['stats'] > 1)
{
   //they refreshed the page or came back here
} else {
   //it's their first time here; your code here
if (!$handle = fopen($logfile, 'r+')) {
	die("Failed to open log file");
}

file_put_contents($logfile, $logline . file_get_contents($logfile));

fclose($handle);
}

?>

Link to comment
Share on other sites

Try switching the include to be before the echo...

 

include ('log.php');
echo "
test log script
";
// phpinfo ();

?>

 

 

I was getting this error if I put the include after the echo:

 

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent

 

You don't get errors because you seem to be a live site, if you put this code at the top of your page you would probably get the same error message:

 

ini_set ("display_errors", "1");
error_reporting(E_ALL);

 

It's still not a logical explanation as to why it keeps writing dupes.  * Back to testing *

Link to comment
Share on other sites

i put the include on the top before the echo, i didn't get any error, but it still keeps logging.

 

i've tried uploading the same scripts to a different host to test... it still doing the same thing.

 

http://picsworld.biz/tt/i.php - the main script to call the log.php

http://picsworld.biz/tt/log.php - the log script

http://picsworld.biz/tt/logv.php - the viewer

 

Link to comment
Share on other sites

Try echoing out the session count to make sure it's incrementing.

 

if($_SESSION['stats'] > 1)
{
   echo "
session # " . $_SESSION['stats'];
} else

 

Also echo it out here just to make sure it's being passed along:

 

session_start();
include ('log.php');
echo "
test log script
";
echo "session # " . $_SESSION['stats'];
// phpinfo ();

?>

 

The include should take care of this but just to rule it out, try putting session_start(); on every page.

Link to comment
Share on other sites

Some things to note:

  • If you comment out the mysql stuff (connection, select_db, and mysql_query) it will print out the query that you would hypothetically be using.
  • I've attached another file, I guess it would be your "i.php" file.  The difference here is that I added a button where you can destroy your session and refresh the page, so you can try different things.

 

log.php)

 

session_start();

//connection information
mysql_connect("localhost", "username", "password") or die(mysql_error());
echo "Connected to MySQL
";
mysql_select_db("statistics") or die(mysql_error());
echo "Connected to Database";

// Getting the information
$ipaddress = $_SERVER['REMOTE_ADDR'];
$page = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$referrer = $_SERVER['HTTP_REFERER'];
$datetime = date('D, M j, Y (T) \a\t h:i:s A');
$useragent = $_SERVER['HTTP_USER_AGENT'];
$remotehost = @getHostByAddr($ipaddress);

$_SESSION['stats'] = (isset($_SESSION['stats'])) ? $_SESSION['stats']+1 : 1;

if($_SESSION['stats'] > 1)
{
//they refreshed the page... don't do anything
echo "We've already stored your stats...";
} 
else 
{
   //it's their first time here; INSERT into the database
   $sql = "INSERT INTO statistics (ipaddress, referrer, datetime, useragent, remotehost, page)
                           VALUES ('$ipaddress', '$referrer', '$datetime', '$useragent', '$remotehost', '$page')";
   mysql_query($sql) or die(mysql_error());
   echo "Successfully recorded your stats: 
$sql";
}
?>

 

 

i.php

 

include "log.php";
echo "OK we're here";

if(isset($_POST['submit'])) {
   session_destroy();
   echo "Session Destroyed...";
}
?>

</pre>
<form action="<?php%20echo%20%24_SERVER%5B'PHP_SELF'%5D;%20?>" method="POST">

<

 

 

Hope this all works for you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.