Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Saturday, October 8, 2016

How to Log Visitors' IP Addresses, OS, and Browser

This tutorial is based on the answers by deceze and Gaurang.

The following code will log the visitor's IP address and access time, OS, and browser:


<?php
$user_agent     =   $_SERVER['HTTP_USER_AGENT'];

function getOS() {
    global $user_agent;
    $os_platform    =   "Unknown OS Platform";
    $os_array       =   array(
                            '/windows nt 10/i'     =>  'Windows 10',
                            '/windows nt 6.3/i'     =>  'Windows 8.1',
                            '/windows nt 6.2/i'     =>  'Windows 8',
                            '/windows nt 6.1/i'     =>  'Windows 7',
                            '/windows nt 6.0/i'     =>  'Windows Vista',
                            '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                            '/windows nt 5.1/i'     =>  'Windows XP',
                            '/windows xp/i'         =>  'Windows XP',
                            '/windows nt 5.0/i'     =>  'Windows 2000',
                            '/windows me/i'         =>  'Windows ME',
                            '/win98/i'              =>  'Windows 98',
                            '/win95/i'              =>  'Windows 95',
                            '/win16/i'              =>  'Windows 3.11',
                            '/macintosh|mac os x/i' =>  'Mac OS X',
                            '/mac_powerpc/i'        =>  'Mac OS 9',
                            '/linux/i'              =>  'Linux',
                            '/ubuntu/i'             =>  'Ubuntu',
                            '/iphone/i'             =>  'iPhone',
                            '/ipod/i'               =>  'iPod',
                            '/ipad/i'               =>  'iPad',
                            '/android/i'            =>  'Android',
                            '/blackberry/i'         =>  'BlackBerry',
                            '/webos/i'              =>  'Mobile'
                        );

    foreach ($os_array as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            $os_platform    =   $value;
        }
    }
    return $os_platform;
}

function getBrowser() {
    global $user_agent;
    $browser        =   "Unknown Browser";
    $browser_array  =   array(
                            '/msie/i'       =>  'Internet Explorer',
                            '/firefox/i'    =>  'Firefox',
                            '/safari/i'     =>  'Safari',
                            '/chrome/i'     =>  'Chrome',
                            '/edge/i'       =>  'Edge',
                            '/opera/i'      =>  'Opera',
                            '/netscape/i'   =>  'Netscape',
                            '/maxthon/i'    =>  'Maxthon',
                            '/konqueror/i'  =>  'Konqueror',
                            '/mobile/i'     =>  'Handheld Browser'
                        );

    foreach ($browser_array as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            $browser    =   $value;
        }
    }
    return $browser;
}

$user_os        =   getOS();
$user_browser   =   getBrowser();

$device_details =   $user_browser." ".$user_os;
$line = date('Y-m-d H:i:s') . " - $_SERVER[REMOTE_ADDR]" . " " . $device_details;

file_put_contents('visitors.log', $line . PHP_EOL, FILE_APPEND);
?>

Make sure that the current directory is owned by www-data.
$ sudo chown www-data:www-data .

You will see a log file visitors.log in the current directory with a log similar to:
2016-10-08 12:33:13 - 12.34.56.78 Chrome Linux

How to Allow a Visitor Upload Image Files on Your Web Server

This post is based on this tutorial with some minor modifications.

If you want to let a visitor upload an image file to your web server, here is how to do. I will assume that you have a http and php server running on your system. If not, please refer to this post.

First, create a simple upload.html file:
<html>
<head>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
            Select image to upload:
                <input type="file" name="fileToUpload" id="fileToUpload">
                <input type="submit" value="Upload Image" name="submit">
    </form>
</html>

Next, create upload.php file:
<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".<br>";
        $uploadOk = 1;
    } else {
        echo "File is not an image.<br>";
        $uploadOk = 0;
    }
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
    echo "Sorry, your file is too large.<br>";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "webp" && $imageFileType != "jxr" ) {
    echo "Sorry, only jpg, jpeg, png, webp, jxr, & gif files are allowed. Also, the extension must be all LOWER case!<br>";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.<br>";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<br>";
        echo "<br>http://SERVER_IP/" . $target_dir . basename( $_FILES["fileToUpload"]["name"]) . "<br>";
    } else {
        echo "Sorry, there was an error uploading your file.<br>";
    }
}
?>
]

Make sure to replace SERVER_IP with your server's IP address. Now, you can browse to your upload.html file, choose an image file, and upload to the server.

Make sure that the target directory is owned by www-data, the web werver.
$ sudo chown www-data:www-data /var/www/html/upload

Make sure to implement more security checks. You surely don't want any random visitor upload random files on the server!

How to Find out Visitor's IP Address

Here is how to find out a visitor's IP address using PHP:
<?php
    echo $_SERVER['REMOTE_ADDR']
?>

You can always embed this in HTML file:
<html>
<head></head>
<body>
    Your IP Address is <?php echo $_SERVER['REMOTE_ADDR'] ?>.
</body>
</html>

Note that the web server must be configured to parse the PHP code inside html file to display it correctly. You may want to refer tho this post to do this in Debian.

How to Setup a Home Web Server on Debian Jessie

Here is how to setup a home web server on Debian Jessie.

First, install apache web server. This will serve html files.
$ sudo apt-get install -y apahce2

If you haven't configured sudo, please take a look at this post to see how to configure sudo in Debian.

Next, install php5. This will server php files.
$ sudo apt-get install -y php5 libapache2-mod-php5

Now, your default server root directory is /var/www/html. You can add your html and php files here for your server to serve.

Finally, you probably may want to serve html files that embed php code in it. To do this, you need to edit /etc/apache2/mods-enabled/php5.conf file and add the following lines:
<FilesMatch ".+\.html$">
   SetHandler application/x-httpd-php
</FilesMatch>

To reload the config file, restart the server:
$ sudo service apache2 restart

Now, create /var/www/html/test.html file with the following code:
<html>
    <body>
        <h1>HTML file with PHP Code</h1>
        <?php
        echo "This code is run by PHP server";
        ?>
    </body>
</html>

In your web browser, go to http://SERVER_IP_ADDRESS/test.html
You should see the following text if your server is properly configured:
HTML file with PHP Code
This code is run by PHP server

By the way, if you want to override the config setting with .htaccses file, you need to edit
/etc/apache2/apache2.conf file and edit to
<Directory /var/www/>
    Options FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Enjoy your web server!