Can I read an external file every set amount of time? - php

I am writing a script where it checks for an updated version from an external server. I use this code in the config.php file to check for latest version.
$data = get_theme_data('http://externalhost.com/style.css');
$latest_version = $data['Version'];
define('LATEST_VERSION', $latest_version);
This is fine and I can fetch the latest version (get_theme_data is WordPress function) but the problem is that it will be executed on every single load which I do not want. I also do not want to only check when a form is submitted for example. Alternatively I was looking into some sort of method to cache the result or maybe check the version every set amount of hours? Is such thing possible and how?

Here, gonna make it easy for you. Store the time you last checked for the update in a file.
function checkForUpdate() {
$file = file_get_contents('./check.cfg', true);
if ($file === "") {
$fp = fopen('./check.cfg', 'w+');
fwrite($fp, time() + 86400);
fclose($fp);
}
if ((int)$file > time()) {
echo "Do not updatE";
} else {
echo "Update";
$fp = fopen('./check.cfg', 'w+');
fwrite($fp, time() + 86400);
fclose($fp);
}
}
You can obviously make this much more secure/efficient if you want to.
Edit: This function will check for update once every day.

A scheduled task like this should be set up as a separate cron or at job. You can still write everything in PHP, just make a script that runs from the command line and does the updating. Checkout "man crontab" for details, and/or check which scheduling services your server is running.

Related

PHP save array for different instances of a script

My PHP script are triggered via POST from different sources.
There is a array, where elements are added and deleted.
I save this array with
$jsonString = json_encode($curList);
file_put_contents("curList.obj", $jsonString);
and read it with
$stringified1 = file_get_contents("curList.obj") ?: '';
$curList = json_decode($stringified1, true) ?: [];
This works usually fine. But now I got in trouble, because several instances are running at the same time and read and write the array in the same time period. This creates problems, because some information are going lost.
It is possible to make sure, that another instance has to be wait, until the read and update of the file is finished?
Or is it possible that only one instance of the script is running at the same time, without a POST get lost?
Thanks to #Maksim I found the following solution:
$file = "curList.obj";
$lock = "curList.lock";
while(true){
if(!file_exists($lock)){
$fHandle = fopen($lock, 'x');
if($fHandle != false)
break;
}
usleep(20);
}
$stringified1 = file_get_contents("curList.obj") ?: '';
$curList = json_decode($stringified1, true) ?: [];
$curList[] = $_POST;
// save array
$jsonString = json_encode($curList);
file_put_contents("curList.obj", $jsonString);
// release lock handle and delete lock
fclose($fHandle);
unlink($lock);
Why this solution.
I am using IIS 10 and there is a problem with IIS and flock. Therefore I build a kind of wrapper around the read and write of the data update.
It is an additional curList.lock file.
First I check if the file exists, if not I create it with fopen($lock, 'x'). The option 'x' only creates the file if it not already exists. Otherwise it will fail and the routine is stil in the while loop, until it get an access.
try use Session in your project. With Sessions you can temporary save different data without conflicts.
This information storage is unique to the user, but is not stored forever

Save SQL data to PHP file

I've faced a problem that I can't solve. Thing I want to do, to "save" all output SQL data to file (which should renew at timed interval ex. 5 mins) and print the file out on the website.
This is my example script, which shows data... but it makes connection each time web is loaded.
<?php
mysql_connect($dbserver, $dblogin, $dbpass);
mysql_select_db($dbname);
mysql_query("SET NAMES 'utf8'");
$rektanrekt = mysql_query("SELECT * FROM characters WHERE (accesslevel < '1') order by pkkills desc LIMIT 10");
$i = 1;
echo '<table id="top_table"><tr id="table_title"><td></td><td> </td><td>Nick</td><td></td><td>Kills</td></tr>';
while($row = mysql_fetch_array($rektanrekt))
{
echo '<tr><td id="skaiciai">' . $i . '.</td><td></td><td id="nickas"><font>';
echo $row["char_name"];
echo '</font></td><td> </td><td id="kills"><font>';
echo $row["pkkills"];
echo '</font></td></tr>';
$i++;
}
echo '</table>';
?>
And it does the job done -> http://prntscr.com/a3hpmx
But is it possible to make "backup" of this file, and show it if SQL is offline ... or even better - if SQL is ON update the file each time interval, if SQL is OFF just show latest one?
Saving output data to file:
The simplest way is to output the results in a text file using code similar to the following:
$timeStamp = time();
$pathName = "/gameLog/".$timeStamp.".txt";
$myFile = fopen($pathName, "w");
//+++++++++++++++++++++++++++++++++++
/*here you place your previous code, and inside the while
loop you use the fwrite() function to include the information
you want to save. For example:
fwrite($myFile, ($info."\n"));
where $info is the data you want to include in the file, and
"\n" is the line break.
*/
//+++++++++++++++++++++++++++++++++++
fclose($myFile);
Note: I used $timeStamp = time(); as the name of the file you are saving with the information you wanted because it will consistently generate a new value, hence you won't be overwriting your log files. Also it can help track at what time this log was saved. You could make this cleaner of course.
Doing this in intervals:
As jeroen mentioned, a cron job is probably your best solution to doing so. If you are using CPanel (linux), when you go to the CPanel homepage of your webhosting account (I am assuming your have an account with godaddy or another provider), there should be an option called "Cron Jobs" or something similar. What a Cron Job does is that it is a "Scheduled Event" that is told to execute some file in an interval you specify (you also specify the directory of your file). I found an example on youtube for you, however the video is a bit out of date, though the process should be similar:
https://www.youtube.com/watch?v=bmBjg1nD5yA
Edited: I noticed you are working on L2Aria, if you need any help, let me know! :)

Prevent PHP from sending multiple emails when running parallel instances

This is more of a logic question than language question, though the approach might vary depending on the language. In this instance I'm using Actionscript and PHP.
I have a flash graphic that is getting data stored in a mysql database served from a PHP script. This part is working fine. It cycles through database entries every time it is fired.
The graphic is not on a website, but is being used at 5 locations, set to load and run at regular intervals (all 5 locations fire at the same time, or at least within <500ms of each-other). This is real-time info, so time is of the essence, currently the script loads and parses at all 5 locations between 30ms-300ms (depending on the distance from the server)
I was originally having a pagination problem, where each of the 5 locations would pull a different database entry since i was moving to the next entry every time the script runs. I solved this by setting the script to only move to the next entry after a certain amount of time passed, solving the problem.
However, I also need the script to send an email every time it displays a new entry, I only want it to send one email. I've attempted to solve this by adding a "has been emailed" boolean to the database. But, since all the scripts run at the same time, this rarely works (it does sometimes). Most of the time I get 5 emails sent. The timeliness of sending this email doesn't have to be as fast as the graphic gets info from the script, 5-10 second delay is fine.
I've been trying to come up with a solution for this. Currently I'm thinking of spawning a python script through PHP, that has a random delay (between 2 and 5 seconds) hopefully alleviating the problem. However, I'm not quite sure how to run exec() command from php without the script waiting for the command to finish. Or, is there a better way to accomplish this?
UPDATE: here is my current logic (relevant code only):
//get the top "unread" information from the database
$query="SELECT * FROM database WHERE Read = '0' ORDER BY Entry ASC LIMIT 1";
//DATA
$emailed = $row["emailed"];
$Entry = $row["databaseEntryID"];
if($emailed == 0)
{
**CODE TO SEND EMAIL**
$EmailSent="UPDATE database SET emailed = '1' WHERE databaseEntryID = '$Entry'";
$mysqli->query($EmailSent);
}
Thanks!
You need to use some kind of locking. E.g. database locking
function send_email_sync($message)
{
sql_query("UPDATE email_table SET email_sent=1 WHERE email_sent=0");
$result = FALSE;
if(number_of_affacted_rows() == 1) {
send_email_now($message);
$result = TRUE;
}
return $result;
}
The functions sql_query and number_of_affected_rows need to be adapted to your particular database.
Old answer:
Use file-based locking: (only works if the script only runs on a single server)
function send_email_sync($message)
{
$fd = fopen(__FILE__, "r");
if(!$fd) {
die("something bad happened in ".__FILE__.":".__LINE__);
}
$result = FALSE;
if(flock($fd, LOCK_EX | LOCK_NB)) {
if(!email_has_already_been_sent()) {
actually_send_email($message);
mark_email_as_sent();
$result = TRUE; //email has been sent
}
flock($fd, LOCK_UN);
}
fclose($fd);
return $result;
}
You will need to lock the row in your database by using a transaction.
psuedo code:
Start transaction
select row .. for update
update row
commit
if (mysqli_affected_rows ( $connection )) >1
send_email();

Email Open Length Tracking with PHP

I have been tracking emails for years using a "beacon" image and for those clients that allow the images to download it has worked great to track how many people have opened the email.
I came across the service "DidTheyReadIt" which shows how long the client actually read the email, I tested it with their free service and it is actually pretty close to the times I opened the email.
I am very curious in how they achieve the ability to track this, I am certain that whatever solution is chosen it will put a lot of load on the server / database and that many of the community will reply with "Stop, No and Dont" but I do want to investigate this and try it out, even if its just enough for me to run a test on the server and say "hell no".
I did some googling and found this article which has a basic solution http://www.re-cycledair.com/tracking-email-open-time-with-php
I made a test using sleep() within the beacon image page:
<?php
set_time_limit(300); //1000 seconds
ignore_user_abort(false);
$hostname_api = "*";
$database_api = "*";
$username_api = "*";
$password_api = "*";
$api = mysql_pconnect($hostname_api, $username_api, $password_api) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_api, $api);
$fileName = "logo.png";
$InsertSQL = "INSERT INTO tracker (FileName,Time_Start,Time_End) VALUES ('$fileName',Now(),Now()+1)";
mysql_select_db($database_api, $api);
$Result1 = mysql_query($InsertSQL, $api) or die(mysql_error());
$TRID = mysql_insert_id();
//Open the file, and send to user.
$fp = fopen($fileName, "r");
header("Content-type: image/png");
header('Content-Length: ' . filesize($fileName));
readfile($fileName);
set_time_limit(60);
$start = time();
for ($i = 0; $i < 59; ++$i) {
// Update Read Time
$UpdateSQL = "UPDATE tracker SET Time_End = Now() WHERE TRID = '$TRID'";
mysql_select_db($database_api, $api);
$Result1 = mysql_query($UpdateSQL, $api) or die(mysql_error());
time_sleep_until($start + $i + 1);
}
?>
The problem with the code above (other than updating the database every second) is that once the script runs it continues to run even if the user disconnects (or moves to another email in this case).
I added "ignore_user_abort(false);", however as there is no connection to the mail client and the headers are already written I dont think the "ignore_user_abort(false);" can fire.
I looked at the post Track mass email campaigns and one up from the bottom "Haragashi" says:
"You can simply build a tracking handler which returns the tracking image byte by byte. After every byte flush the response and sleep for a period of time.
If you encounter a stream closed exception the client has closed the e-mail (deleted or changed to another e-mail who knows).
At the time of the exception you know how long the client 'read' the e-mail."
Does anyone know how I could "simply build a tracking handler" like this or know of a solution I can implement into my code that will force the code to stop running when the user disconnects?
I think the problem is that you aren't doing a header redirect every so often. The reason that it is necessary is because once a script starts executing in PHP+Apache, it basically disregards the client until finished. If you force a redirect every X seconds, it makes the server re-evaluate if the client is still connected. If the client isn't connected, it can't force the redirect, and therefore stops tracking the time.
When I played around with this stuff, my code looked like:
header("Content-type: image/gif");
while(!feof($fp)) {
sleep(2);
if(isset($_GET['clientID'])) {
$redirect = $_SERVER['REQUEST_URI'];
} else {
$redirect = $_SERVER['REQUEST_URI'] . "&clientID=" . $clientID;
}
header("Location: $redirect");
exit;
}
If the client id was set, then above this block of code I would log this attempt at reading the beacon in the database. It was easy to simply increment the time on email column by 2 seconds every time the server forced a redirect.
Would you not do something more like this:
<?php
// Time the request
$time = time();
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);
// Run a pointless loop that sometime
// hopefully will make us click away from
// page or click the "Stop" button.
while(1)
{
// Did the connection fail?
if(connection_status() != CONNECTION_NORMAL)
{
break;
}
// Sleep for 1 seconds
sleep(1);
}
// Connention is now terminated, so insert the amount of seconds since start
$duration = time() - $time;

PHP: Most efficient way to make multiple fsockopen(); connections?

Hey guys i'm making a website where you submit a server for advertising. When the user goes to the index page of my website it grabs the ip's of all the servers submitted and then tests to see if it is online using fsockopen() like so:
while($row = mysql_fetch_assoc($rs)) {
$ip = $row['ip'];
$info = #fsockopen($ip, 25565, $errno, $errstr, 0.5);
if($info) {
$status = "<div><img width='32px' height='32px'
title='$name is online!' src='images/online.png'/></div>";
$online = true;
} else {
$status = "<div><img width='32px' height='32px'
title='$name is offline!' src='images/offline.png'/></div>";
$online = false;
}
}
}
This way works fine, but the only downside is when you load the site it takes a good 2-4 seconds to start loading the website due to the fsockopen() methods being called. I want to know if there is a better way to do this that will reduce the amount of wait time before the website loads.
Any information will be appreciated, thanks.
Store the online status and last check time in a database, if the last check time is longer than 15 minutes for example, update it. I am pretty sure you don't need to get the status on EVERY pageload? It's the time it takes to connect to each server that slows down the website.
Then again, you would probably wanna move the update process to a cronjob instead of relying on someone visiting your website to update the server statuses.
Looking at your example, I'd make all the $status bits be javascript calls to another php page that checks that individual server.
However, the idea to move the status checks to cron job or use some kind of status caching is very good too. Maybe store statuses in a database only only check the ones that have expired (time limit set by you).

Categories