Reputation:
I have a website and I want to track all user-agents that visit it. And save all the user-agents on a file, or send by email. How can I achieve that in PHP or JS?
Upvotes: 0
Views: 929
Reputation: 320
For PHP you can use: https://github.com/ua-parser/uap-php and append each detected user-agent to txt file via php:
require_once 'vendor/autoload.php';
use UAParser\Parser;
$ua = $SERVER['HTTP_USER_AGENT'];
$parser = Parser::create();
$result = $parser->parse($ua);
$fp = fopen('user-agents.txt', 'a'); //opens file in append mode
fwrite($fp, $result->ua->toString());
fclose($fp);
Note, using the library gives you many options to receive wanted data from user-agent. For example for user-agent 'Mozilla/5.0 (Macintosh; Intel Ma...' you can achieve that data:
print $result->ua->family; // Safari
print $result->ua->major; // 6
print $result->ua->minor; // 0
print $result->ua->patch; // 2
print $result->ua->toString(); // Safari 6.0.2
print $result->ua->toVersion(); // 6.0.2
print $result->os->family; // Mac OS X
print $result->os->major; // 10
print $result->os->minor; // 7
print $result->os->patch; // 5
print $result->os->patchMinor; // [null]
print $result->os->toString(); // Mac OS X 10.7.5
print $result->os->toVersion(); // 10.7.5
print $result->device->family; // Other
print $result->toString(); // Safari 6.0.2/Mac OS X 10.7.5
print $result->originalUserAgent; // Mozilla/5.0 (Macintosh; Intel Ma...
Upvotes: 0
Reputation: 847
OK, three things need to happen. Write the file, mail the contents and clear the file after mailing. the first part will be in a separate file, whilst the mail and file clearing will be in another file
<?php
// get the user agent
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// write to file
file_put_contents( 'user_agents.log', $user_agent, FILE_APPEND );
?>
<?php
// fetch the list of user agents from the file
$body = file_get_contents( 'user_agents.log' );
// mail to whereva
mail( '[email protected]', 'User Agent Log', $body );
// truncate the file back to zero
$fh = fopen( 'user_agents.log', 'w' );
fclose($fh);
?>
Upvotes: 1