Create a new, completely empty PHP file called functions.php and add a PHP block. This file will be included in all other pages to log the user's details to a text file. It will also do other things such as checking if a use is logged in and later on it will connect to a database. Start with the one to create the text log file:
- create the basic structure of a function and give it a name suited to logging visits
- from $_SERVER get the user's IP address, their browser (user agent) and the name of the page they are visiting and place them into variables
- using PHP generate a simple but reasonably complete time and date and store that in a variable as well
- create a new PHP block at the top of index.php
- include functions.php in the new PHP block
- under the include line call the new logging function by name so the code is run and can now be tested for errors (it won't do anything yet)
- write the content of the variables to a file called log.txt (note this is not secure but we will fix that later)
- use \t and \r\n to structure the file with all the details of one visit on one line
Test it and you should have a text file on the server (remember to refresh if using FTP) containing the visitor's details and the page they visited.
Copy the PHP block with the include line and the function call line to the top of the other three PHP site pages so that it will be used on all.
User agent string
A typical user agent string looks like this which is probably too long for the file to then be readable:
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
Use an if with some elseif statements after the code for step 2 above which recognises (using strpos) at least four of the main browsers and gives a shortened version of it (e.g. for the above user agent string it might be Firefox). Alter your code for step 7 above so that the shortened versions are stored in the file instead of the full string. If the browser is not recognised write unknown to the file. You should be able to easily find Web pages which explain most current user agent strings.