views:

97

answers:

4

please look at the simple php webpage code below

how can modify my code so that a log file is created on my server which logs each visitor's ip and whether it was successfully redirected to the correct page . something like that.

   <?php

$a = $_SERVER['REMOTE_ADDR'];
if ( $a == "117.96.112.122" )
{
        header("Location: ad_sams_mobile.html");
        return true;
}
else
{
        header("Location: ad_other_mobile.html");
        return true;
}

?>
+2  A: 

See the PHP function file_put_contents. You'll need to use the append flag:

file_put_contents("log.txt", "IP: ". $a .", Location: ad_other_mobile.html", FILE_APPEND);
Andy E
A: 

Something like this:

$logfile = 'redirect.log';
$handle = @fopen($logfile, "a");

$a = $_SERVER['REMOTE_ADDR'];

if ( $a == "117.96.112.122" )
{
    $redirect_loc = 'ad_sams_mobile.html';
    header("Location: {$redirect_loc}");
 }
else
{
    $redirect_loc = 'ad_other_mobile.html';
    header("Location: {$redirect_loc}");
}

if ($handle && is_writable($logfile))
{
    $log = "{$a} -> {$redirect_loc}\n";
    fwrite($handle, $log);
    fclose($handle);
}
return true; // you always return true so just put it at the end
Michal M
I prefer file_put_contents, you don't need to open a handle to the file or check that it's writable, it will just return false if it can't write.
Andy E
Wasn't sure and didn't bother to check actually so I just made a double precaution. Thanks for the info though.
Michal M
+1  A: 

The Apache access.log should have all the information you need.

All you have to do is parse it.

partoa
What if he's not using Apache? Also, parsing the log programmatically would be much more difficult that simply updating a text file with the IP address.
Andy E
Andy: A text file would still need to be parsed if any analysis were to be done on the logs and if no analysis needs to be done, then whats the point of logging. At the end of the day, parsing is an unavoidable pain. If you're too lazy to parse log files, maybe a DB would do, but honestly, how difficult can a grep be? With that said I expect all web servers to have some kind of access log, Apache and IIS do, I know for sure. As far as I can tell, logging from your PHP app is reinventing the wheel while adding unnecessary overheads to your app.
partoa
A: 

Or this for IP logging:

<?php
$file = fopen("log.html", "a");

$time = date("H:i dS F");
fwrite($file, "<b>Time:</b> $time<br/>" );

if( $REMOTE_ADDR != null)
{
fwrite($file,"<b>IP address:</b> $REMOTE_ADDR<br/>");
}

if( $HTTP_REFERER != null)
{
fwrite($file,"<b>Referer:</b> $HTTP_REFERER<br/>");
}

fwrite($file,"<b>Browser:</b> $HTTP_USER_AGENT<hr/>");

fclose($file)

?>
Newb
> $HTTP_USER_AGENTSeriously, start using SuperGlobals. Will save you tons of headaces once your PHP Server Administrator decides to finally set register_globals to false (as it should be). See http://www.php.net/manual/en/faq.using.php#faq.register-globals
Martin Hohenberg