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
Related
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');
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.
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!");
}
?>
I have a community site, where people can put up pages, and the url generates from their name. e.g. My Business, becomes my-business. I want to create a way, that if there is another My Business, it will check and make the url my-business-2, my-business-3, etc.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$slugs = array();
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
if(in_array($url, $slugs)) {
$max = 1;
while(in_array(($url . '-' . ++$max ), $slugs)) $url .= '-' . $max;
}
}
return $url;
}
This is my function, but this still wont work, as if there is a business called My Bus, it will make it my-bus-2, when it would have been unique at my-bus. I have experimented with other functions too, but this one is the closest I got. Can anyone tell me one that works perfectly?
So form my understanding, you are trying to avoid inserting/generating duplicate URL. Output will be something like this -
www.example.com/my-business
www.example.com/my-business-1
www.example.com/my-business-2
www.example.com/my-business-3
...
Try using this function -
function check_url($base_url, $new_url='', $num=0) {
if($new_url == '') {
$new_url = $base_url;
}
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url = '$new_url'");
if(mysqli_num_rows($qry) > 0) {
while($row = mysqli_fetch_array($qry)) {
$num++;
check_url($base_url, $base_url . '-' . $num, $num);
}
}
return $url;
}
Basically, this function will check the database until it finds a valid URL. Each time it will increment the number and recursively call the same function to generate new/valid URL.
Simple and basic!
#SpritsDracula has working code, but his function will query your database each time it executes. That being said, the recursion is a nice concept. Here is a piece of code that will save your the multiple database calls.
function check_url($url) {
$qry = mysqli_query($this->con, "SELECT * FROM businesses WHERE url LIKE '$url%'");
if(mysqli_num_rows($qry)>0) {
$baseUrl = $url;
$slugs = [];
while($row = mysqli_fetch_array($qry)) $slugs[] = $row['url'];
$max = 1;
while(in_array($url, $slugs)) {
$url = $baseUrl . "-" . $max++;
}
}
return $url;
}
am trying to get progress of all the files being copied.
$qryStr = explode(",",$_POST['data']);
$timestamp=$_POST['timestamp'];
$size=sizeof($qryStr);
//echo $size;
$offset=100/$size;
$progress=0;
$_SESSION[$timestamp]=$progress;
session_start();
foreach($qryStr as $value) {
$src = $value;
$dest = "../home/tmp/";
$cmd = 'scp '.$src.' '.$dest.'';
sleep(1);
$progress+=$offset;
$_SESSION[$timestamp] = ceil($progress);
var_dump($_SESSION[$timestamp]);
$result = shell_exec($cmd);
}
code to get progress stored in session
session_start();
var_dump($_SESSION['timestamp']);
getProgress($_GET['timestamp']);
function getProgress($timestamp) {
if (isset($_SESSION[$timestamp])) {
echo json_encode(array("progress" => $_SESSION[$timestamp]));
} else {
echo json_encode(array("progress" => -1));
}
}
when i try to accesss the session data , am getting it as null. any problem in my script.
You have used $timestamp in the following line,
$_SESSION[$timestamp] = ceil($progress);
Instead, use
$_SESSION['timestamp'] = ceil($progress);
Only then it will be available in $_SESSION['timestamp'], else will be in $_SESSION['2013-10-28 14:33:00'], something like that which is non-generic.