Total visitor counter to my existing counter for Wordpress - php

I am making a simple visitor counter without MySQL in a WordPress plugin. To achieve this I make a simple text visitor.db where store visitor ip for a while and show the total number of IPs as current online visitor and after a time period the history log delete. But now I want to implement from that visitor.db to save them another.db where it count total visitor till today. Is it possible?
If I count while loop ? how can I save it to another.db
$counter = 0;
while(..) {
$counter++;
}
echo $counter;
For example now it show Online : 70
But I want to achieve Total : 145875458 Online : 70 something like this
define('VISITOR_DATA_PATH',plugin_dir_path( __FILE__ ));
$dbfile = VISITOR_DATA_PATH . "visitors.db";
$expire = 300; // average time in seconds to consider someone online before removing from the list
if(!file_exists($dbfile)) {
die("Error: Data file " . $dbfile . " NOT FOUND!");
}
if(!is_writable($dbfile)) {
die("Error: Data file " . $dbfile . " is NOT writable! Please CHMOD it to 666!");
}
function getIPs() {
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
elseif(isset($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];
else $ip = "0";
return $ip;
}
function CountVisitors() {
global $dbfile, $expire;
$cur_ip = getIPs();
$cur_time = time();
$dbary_new = array();
$dbary = unserialize(file_get_contents($dbfile));
if(is_array($dbary)) {
while(list($user_ip, $user_time) = each($dbary)) {
if(($user_ip != $cur_ip) && (($user_time + $expire) > $cur_time)) {
$dbary_new[$user_ip] = $user_time;
}
}
}
$dbary_new[$cur_ip] = $cur_time; // add record for current user
$fp = fopen($dbfile, "w");
fputs($fp, serialize($dbary_new));
fclose($fp);
$out = sprintf("%3d", count($dbary_new)); // format the result to display 3 digits with leading 0's
return $out;
}
function visitor_counter_shrocode(){
$visitors_online = CountVisitors();
ob_start();
$output='<span> Online: <b>'.$visitors_online.'</b></span>';
ob_end_clean();
return $output;
}
add_shortcode('onlinevisitor','visitor_counter_shrocode');

Related

Scrape E-Mails using IMAP without Exceeding Bandwidth

I have the following code which works great to do what it is meant to do. It scrapes bodys of all e-mails in the inbox at an e-mail address using IMAP and retrieves the unique code sent inside the body and stores it in a database with the amount paid. I'm hoping to make it so when a user purchases something they can send an Interac e-transfer and then enter the code that both of us receive via e-mail in the website and it will apply the credit of the e-transfer to their account/purchase.
However; after setting it up on a cron job to cycle every few minutes so the content in the database stays fresh it eventually exceeds the bandwidth for the account within a day or so (not positive on how long it took but it didn't take long). Now, like I said the code works it's just very resource intensive apparently.
I do not pipe the script because the e-mail account has already been set up a while ago and we do use the account for other e-transfers which I review manually for other transactions.
Is there anyway to clean it up so it works the same but uses less resources/bandwidth?
Would it be better to run it when a user enters their payment code? Depending on the number of users running it this could also lead to bandwidth troubles.
Is there any improvements or what ideas do you have?
define("MAX_EMAIL_COUNT", $_POST['maxcount']);
/* took from https://gist.github.com/agarzon/3123118 */
function extractEmail($content) {
$regexp = '/([a-z0-9_\.\-])+\#(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
preg_match_all($regexp, $content, $m);
return isset($m[0]) ? $m[0] : array ();
}
function getAddressText(&$emailList, &$nameList, $addressObject) {
$emailList = '';
$nameList = '';
foreach ($addressObject as $object) {
$emailList .= ';';
if (isset($object->personal)) {
$emailList .= $object->personal;
}
$nameList .= ';';
if (isset($object->mailbox) && isset($object->host)) {
$nameList .= $object->mailbox . "#" . $object->host;
}
}
$emailList = ltrim($emailList, ';');
$nameList = ltrim($nameList, ';');
}
function processMessage($mbox, $messageNumber) {
global $db;
// get imap_fetch header and put single lines into array
$header = imap_rfc822_parse_headers(imap_fetchheader($mbox, $messageNumber));
$timestamp = strtotime($header->Date);
$fromEmailList = '';
$fromNameList = '';
if (isset($header->from)) {
getAddressText($fromEmailList, $fromNameList, $header->from);
}
$toEmailList = '';
$toNameList = '';
if (isset($header->to)) {
getAddressText($toEmailList, $toNameList, $header->to);
}
$body = imap_fetchbody($mbox, $messageNumber, 1);
//echo "<pre>".print_r($body,true)."</pre>";
/* Find Reference Number */
//echo "<pre style='background-color: #A2A2A2; border: 1px solid black'>$body</pre>";
$searchfor = 'Reference Number';
// get the file contents, assuming the file to be readable (and exist)
$contents = $body;
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$reference = trim(str_replace('Reference Number : ','',$matches[0][0]));
}
else{
}
/* Find Amount Paid */
//echo "<pre style='background-color: #A2A2A2; border: 1px solid black'>$body</pre>";
$searchfor = 'has sent you a money transfer for the amount of';
// get the file contents, assuming the file to be readable (and exist)
$contents = $body;
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$amount = trim(preg_replace("/[^0-9\.]/", "",$matches[0][0]),'.');
}
else{
}
$bodyEmailList = implode(';', extractEmail($body));
// Delete all messages older than one year (31557600 seconds). Divide it by two for six months.
if($timestamp < time()-31557600) {
if(imap_delete($mbox,$messageNumber)) {
/*echo "<strong>";
print_r($messageNumber . ' , ' . date("F j, Y g:i A",$timestamp).' , ' . 'Deleted' . "\n");
echo "</strong>";*/
}
}
else {
if(!empty($reference) && !empty($amount)) {
if($fromNameList == "catch#payments.interac.ca" && $toNameList!='etransfers#example.com') {
$query = "SELECT * FROM `".$db->prefix."payments_etransfer` WHERE `reference_id` = '".$reference."'";
$select = $db->select($query);
if($db->num_rows($select) > 0) {
}
else {
$do = $db->insert_sql("INSERT INTO `".$db->prefix."payments_etransfer` SET
`email_id` = '".$messageNumber."',
`timestamp` = '".$timestamp."',
`reference_id` = '".$reference."',
`amount` = '".$amount."',
`sender` = '".$fromEmailList."'");
if($do) {
}
else {
echo "Error<br><blockquote><pre>";
print_r($messageNumber . ',' . $timestamp. ',' . $reference . ',$' . $amount .
',' . $fromEmailList . ',' . $fromNameList
. ',' . $toEmailList . ',' . $toNameList
. ',' . $bodyEmailList . "\n"
);
echo "</pre></blockquote>";
}
}
}
}
}
}
// imap_timeout(IMAP_OPENTIMEOUT, 300);
// Open pop mailbox
if (!$mbox = imap_open($_POST['mailbox'], $_POST['login'], $_POST['password'])) {
die('Cannot connect/check pop mail! Exiting');
}
if ($hdr = imap_check($mbox)) {
$msgCount = $hdr->Nmsgs;
} else {
echo "Failed to get mail";
exit;
}
/* echo "<pre>";
echo 'emails count=' . $msgCount . "\n\n\n";
echo "record number,from emails list,from names list,to emails list, to names list,extracted from body\n";
*/
/* might improve performance according to
http://www.php.net/manual/en/function.imap-headerinfo.php#98809
imap_headers($mbox);
*/
for ($X = $msgCount; $X > 0; $X--) {
if($X > 0) {
processMessage($mbox, $X);
}
}
/*echo "</pre>";*/
imap_expunge($mbox);
imap_close($mbox);
/*

phpscript stops after 4th sleep

I have a csv file containing about 3500 user's data. I want to import these users to my database and send them an email that they are registered.
I have the following code:
public function importUsers()
{
$this->load->model('perk/engagement_model');
$this->load->model('user/users_model');
$this->load->model('acl/aclUserRoles_model');
$allengagements = $this->engagement_model->getAll();
$filename = base_url() . 'assets/overdracht_users.csv';
$file = fopen($filename, "r");
$count = 0;
$totalImported = 0;
$importFails = array();
$mailFails = array();
while (($mappedData = fgetcsv($file, 10000, ";")) !== FALSE)
{
$count++;
//Skip first line because it is the header
if ($count > 1) {
if (!empty($mappedData[0])) {
$email = $mappedData[0];
$user = $this->users_model->getByEmail($email);
if (!$user) {
$user = new stdClass();
$user->email = $mappedData[0];
$user->first_name = $mappedData[1];
$user->family_name = $mappedData[2];
$user->address_line1 = $mappedData[3];
$user->address_postal_code = $mappedData[4];
$user->address_city = $mappedData[5];
$user->address_country = 'BE';
$user->volunteer_location = $mappedData[5];
$user->volunteer_location_max_distance = 50;
$user->phone = $mappedData[6];
if (!empty($mappedData[7])) {
$user->birthdate = $mappedData[7] . "-01-01 00:00:00";
} else {
$user->birthdate = null;
}
foreach ($allengagements as $eng) {
if ($eng->description == $mappedData[8]) {
$engagement = $eng->engagement_id;
}
}
$user->engagement = $engagement;
if (!empty($mappedData[9])) {
$date_created = str_replace('/', '-', $mappedData[9]);
$date_created = date('Y-m-d H:i:s', strtotime($date_created));
} else {
$date_created = date('Y-m-d H:i:s');
}
$user->created_at = $date_created;
if (!empty($mappedData[10])) {
$date_login = str_replace('/', '-', $mappedData[10]);
$date_login = date('Y-m-d H:i:s', strtotime($date_login));
} else {
$date_login = null;
}
$user->last_login = $date_login;
$user->auth_level = 1;
$user->is_profile_public = 1;
$user->is_account_active = 1;
$combinedname = $mappedData[1] . $mappedData[2];
$username = str_replace(' ', '', $combinedname);
if (!$this->users_model->isUsernameExists($username)) {
$uniqueUsername = $username;
} else {
$counter = 1;
while ($this->users_model->isUsernameExists($username . $counter)) {
$counter++;
}
$uniqueUsername = $username . $counter;
}
$user->username = $uniqueUsername;
$userid = $this->users_model->add($user);
if (!empty($userid)) {
$totalImported++;
//Add the user in the volunteer group in ACL
$aclData = [
'userID' => $userid,
'roleID' => 1,
'addDate' => date('Y-m-d H:i:s')
];
$this->aclUserRoles_model->add($aclData);
//Registration mail to volunteer
$mail_data['name'] = $user->first_name . ' ' . $user->family_name;
$mail_data['username'] = $user->username;
$this->email->from(GENERAL_MAIL, 'Test');
$this->email->to($user->email);
//$this->email->bcc(GENERAL_MAIL);
$this->email->subject('Test');
$message = $this->load->view('mail/register/registration',$mail_data,TRUE);
$this->email->message($message);
$mailsent = $this->email->send();
if (!$mailsent) {
array_push($mailFails, $mappedData);
}
} else {
array_push($importFails, $mappedData);
}
if ($count % 50 == 0) {
var_dump("count is " . $count);
var_dump("we are sleeping");
$min=20;
$max=40;
$randSleep = rand($min,$max);
sleep($randSleep);
var_dump("end of sleep (which is " . $randSleep . "seconds long)");
}
var_dump($user);
} else {
array_push($importFails, $mappedData);
}
}
}
}
var_dump("Totale aantal rijen in het bestand (met header) : " . $count);
var_dump("Totale aantal geimporteerd in de database : " . $totalImported);
var_dump("Totale aantal gefaalde imports in de database : " . count($importFails));
var_dump("Deze zijn gefailed : ");
var_dump($importFails);
}
If I do not add the users in the database, or send out a mail, and just var_dump() the $user, i can see all 3500+ users being correctly created in php objects (so they should be able to be inserted correctly).
The problem is that I want to add in a random sleep, between 20 and 40 seconds after every 50 mails that I sent.
So I started doing some testing and after commenting out the insert and mail code, I started running the script, noticing that after some amount (not 50 at all), it just stops for a bit, then continues and shows me the the var_dumps in my if case at the bottom, it can be shown here in the screenshots below.
The first screenshot shows the code stopping for a bit (note that I am only var_dumping stuff, i am not adding something in the database or sending out an email yet).
This screenshot shows what happens after the script reaches 200:
The script just completely stops from this point on. I have tried this 3 times, and every single time it stops exactly on 200.
What is happening here??
Most likely you're hitting default PHP limits. temporarily remove PHP default limits with:
ini_set('memory_limit',-1);
set_time_limit(0);
then, rerun the script and check your output.
There can be multiple reasons, but to know the exact one please enable error output with.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
and if limits are not the problem, the errors will tell you more.
HINT: using logs are still better than outputting errors to the visitors, but my guess is you're testing this on your computer.

Need help caching json_decode(file_get_contents('api')) on wordpress website

I'm trying to retrieve data from coinmarketcap's api and store the data to cache file. If the cache file is older than 10 minutes, retrieve new data and store to cache file. I have been able to get everything to work, except for caching the data. The cache file is never created in the plugin directory. Any help would be appreciated. Here is the code :
function Tickers($data){
foreach($data as $item){
echo "$item->symbol";
echo "<br>";
echo '<span>$' . $item->price_usd . '</span>';
echo "<br>";
echo "<br>";
}
}
function getdata(){
$time = 600; //seconds
$cache_file = 'wp-content/plugins/cryptocurrency_tickers/cache.txt';
if(file_exists($cache_file)){
if(time() - filemtime($cache_file) > $time) {
// too old , re-fetch
$data = json_decode(file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20'));
file_put_contents(cache_file,json_encode($data));
}
else{
//data is current
}
}else {
// create cache
$data = json_decode(file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20'));
file_put_contents(cache_file, json_encode($data));
}
$data = json_decode(file_get_contents($cache_file));
Tickers($data);
}
Look at your code again, missing '$' in front of 'cache_file' on file_put_contents
file_put_contents(cache_file,json_encode($data));
should be
file_put_contents($cache_file,json_encode($data));
Also when you get the json data from the API first you decode, then encode, why you didn't save the data directly from the API, it's already json encoded.
Better version of your code:
function Tickers($data){
foreach($data as $item){
echo "$item->symbol";
echo "<br>";
echo '<span>$' . $item->price_usd . '</span>';
echo "<br>";
echo "<br>";
}
}
function getdata(){
$time = 600; //seconds
$cache_file = '/path/to/cache.txt';
if(file_exists($cache_file)){
if(time() - filemtime($cache_file) > $time) {
// too old , re-fetch
$data = file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20');
file_put_contents($cache_file, $data);
} else{
//data is current
}
} else {
// create cache
$data = file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20');
file_put_contents($cache_file, $data);
}
$data = json_decode(file_get_contents($cache_file));
Tickers($data);
}
getdata();
Also make sure the plugin directory is writable by your web server user.

Compare last GPS and current GPS data

I have a project where i need to send GPS coordinates via. socket in every 6 seconds. The coordinates are stored in a MYsql database. I run a query every 6 seconds and if the last position is different from the current position the application sends the data to the remote server. In the browser it works like a charm but in the terminal i can't use Sessions.
I tried apc_add but according to the PHP manual it is removed a long time ago.
What is the most common way to do a comparsion like that? Store the last coordinates into the database or a text file? Or is there a way to sotore it in run time?
**Here is my main code: **
<?php
require 'bootstrap.php';
use App\Libs\appServiceProvider;
use App\Libs\socketServiceProvider;
use Socket\Raw\Factory;
use App\Models\Koordinata;
$app = new appServiceProvider;
if (empty($_SESSION['lat']) || empty($_SESSION['lon'])) {
$_SESSION['lat'] = 0;
$_SESSION['lon'] = 0;
}
$lastLat = $_SESSION['lat'];
$lastLon = $_SESSION['lon'];
$currentLat = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lat;
$currentLon = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lon;
if ($lastLat != $currentLat && $lastLon != $currentLon) {
$factory = new Factory();
$socket = $factory->createClient('REMOTEADDRESSE');
echo "Kapcsolat létrehozva\n";
$socket->write("MESSAGE");
echo "Üzenet elküldve\n";
var_dump("Válasz: " . $socket->read(8192));
$socket->close();
} else {
echo "Idle";
$log->addDebug("GPS data NOT CHANGED! STATUS IDLE!");
}
$_SESSION['lat'] = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lat;
$_SESSION['lon'] = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lon;
?>
Okay, I did it with database and works fine. Here is the code:
<?php
require 'bootstrap.php';
use App\Libs\appServiceProvider;
use App\Libs\socketServiceProvider;
use Socket\Raw\Factory;
use App\Models\Koordinata;
use App\Models\TempKoordinata;
$app = new appServiceProvider;
$last = TempKoordinata::find(1);
if(!empty($last)) {
$lastLat = $last->lat;
$lastLon = $last->lon;
} else {
$temp = new TempKoordinata();
$temp->id = 1;
$temp->lat = 0;
$temp->lon = 0;
$temp->save();
$log->addDebug('No data to compare! Empty tempCoordinate table! Set values to ZERO!');
}
$currentLat = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lat;
$currentLon = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lon;
if ($lastLat != $currentLat && $lastLon != $currentLon) {
/*$factory = new Factory();
$socket = $factory->createClient('REMOTE');
echo "Kapcsolat létrehozva\n";
$socket->write("MESSAGE");
echo "Üzenet elküldve\n";
var_dump("Válasz: " . $socket->read(8192));
$socket->close();*/
echo "Sending\n";
} else {
echo "Idle\n";
$log->addDebug("GPS data NOT CHANGED! STATUS IDLE!");
}
TempKoordinata::destroy(1);
//Elmentjük a mostani GPS koordinátát
$count = TempKoordinata::all();
//Ha üres az adatbázis akkor elmentjük a koordinátákat
if ($count->count() == 0) {
$temp = new TempKoordinata();
$temp->id = 1;
$temp->lat = $currentLat;
$temp->lon = $currentLon;
$temp->save();
} else {
$log->addDebug("More than one item in the temp table!");
}
?>

PHP - Don't Count Users from index.php

I have a basic online visitors counter. I get it from here. It works verry well but I have a issue. I use it on online game and I have multiple servers. I use it for server online counter. I did add counter pages to the servers via iframe and it counts very well.
But the problem is, I want to display that numbers on index (index.php) page. But when I use :
<?php include("server1.php");?>
it counts index page users as well. I don't want this. How can I make it don't count IP's from index.php?
Here, my codes
Counter (server1.php)
<?php
$dbfile = "game/database/1.db"; // path to data file
$expire = 100; // average time in seconds to consider someone online before removing from the list
if(!file_exists($dbfile)) {
die("Error: Data file " . $dbfile . " NOT FOUND!");
}
if(!is_writable($dbfile)) {
die("Error: Data file " . $dbfile . " is NOT writable! Please CHMOD it to 666!");
}
function CountVisitors() {
global $dbfile, $expire;
$cur_ip = getIP();
$cur_time = time();
$dbary_new = array();
$dbary = unserialize(file_get_contents($dbfile));
if(is_array($dbary)) {
while(list($user_ip, $user_time) = each($dbary)) {
if(($user_ip != $cur_ip) && (($user_time + $expire) > $cur_time)) {
$dbary_new[$user_ip] = $user_time;
}
}
}
$dbary_new[$cur_ip] = $cur_time; // add record for current user
$fp = fopen($dbfile, "w");
fputs($fp, serialize($dbary_new));
fclose($fp);
$out = sprintf("%03d", count($dbary_new)); // format the result to display 3 digits with leading 0's
return $out;
}
function getIP() {
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
elseif(isset($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];
else $ip = "0";
return $ip;
}
$visitors_online = '0'+CountVisitors();
?>
<?=$visitors_online;?>
Iframe (I use it on server pages)
<iframe name="visitors" src="../1.php" width="1" hidden="true" height="1" frameborder="0" scrolling="no"></iframe>
php include (index.php)
Server 7 - Online Players:<?php include("7.php");?>
make a server2.php with this code
<?php
$dbfile = "game/database/1.db"; // path to data file
$expire = 100;
if(!file_exists($dbfile)) {
die("Error: Data file " . $dbfile . " NOT FOUND!");
}
if(!is_writable($dbfile)) {
die("Error: Data file " . $dbfile . " is NOT writable! Please CHMOD it to 666!");
}
function CountVisitors() {
global $dbfile, $expire;
$cur_time = time();
$dbary_new = array();
$dbary = unserialize(file_get_contents($dbfile));
if(is_array($dbary)) {
while(list($user_ip, $user_time) = each($dbary)) {
if(($user_time + $expire) > $cur_time) {
$dbary_new[$user_ip] = $user_time;
}
}
}
$out = sprintf("%03d", count($dbary_new)); // format the result to display 3 digits with leading 0's
return $out;
}
$visitors_online = '0'+CountVisitors();
?>
<?=$visitors_online;?>
and use it like server1.php

Categories