In my folder cache, i have dozens of files whose name is filename-number.json, like
sifriugh-80.json
dlifjbhvzique-76.json
dfhgzeiuy-12.json
...
I have a simple script that cleans my cache dir every 2 hours, deleting files older than 2 hours:
$fileSystemIterator = new FilesystemIterator('cache');
$now = time();
foreach ($fileSystemIterator as $file) {
if ($now - $file->getCTime() >= 3 * 3600) // 2 hours
unlink('cache/' . $file->getFilename());
}
Now, i'm looking to only delete every 2 hours files whose number (before .json but not if number is present at the beginning of the file) does NOT end by -100.json, and those ending by -100.json, every 7 days only.
I know that i can use preg_match() to get names, but is there any effective way to perform it?
There is much simpler way than regex using PHP 8+ str_ends_with() : https://www.php.net/manual/en/function.str-ends-with.php
if (str_ends_with($file->getFilename(), '100.json)) {
// unlink at needed time
} else {
// unlink at needed time
}
For PHP 7, there are several ways to emulate it, check at the bottom of https://www.php.net/manual/en/function.str-ends-with.php
I do not see why you should not use preg_match. It is so good here.
Before using preg_match you should check the first symbol in file name and skip the next code if it is_numeric.
If it is not numeric you need to get only ending "-" can be presented zero or ones + number 1 or more digits + .json ending
(pattern can be something like this /-?\d+\.json$/)
After that you can parse it and know the real number before .json,
Your verification will be something like
If "-" symbol exists and number is 100 check the date for 7 days
If number is not 100 check the date for 2 hours
Related
I'm simply trying to check if the time is either above 9am or below 6pm, the 6pm check works fine and displays the data where as 9am one does nothing but works when changed to 10am.
Here is the line of code I'm using
elseif ((($data[6]) < "09:00") || (($data[6]) > "18:00"))
{
$contact[] = $data;
}
So, let us assume that your time format is always hh:mm. You want to check if the time is between 9 and 18 hours. The problem in your code, as you described, comes when you are check again 09:mm. As it strips away the minute part and just compares the hours.
I would try something like this:
elseif ( implode("", explode(":", $data[6])) > 900 && implode("", explode(":", $data[6])) < 1800)
I will explain the approach step by step.
First of all, this code checks if the date is within the range of 09:00 to 18:00. The code you have provided tested if it is less than 9 or more than 18.
Let us focus on one part of the code, that will explain the whole thing as well:
implode("", explode(":", $data[6])) > 900
First, we separate hours and minutes using the explode function. This gives us an array with two values.
`[0] => hh,`
`[1] => mm`
Now that we have separated this value we implode or concatenate them using the implode function that has no separator.
Next, instead of testing against the string, we test against the number. 09:00 is the same as 900 in this case.
Thus, we can check if the time is within the required limits.
First of all, I know I am not supposed to as "code sample" here. Sadly, I am not a programmer and I have a situation where I need to update a line in a report to present to the customer, but I do not know how to do it.
I have access to PHP file report.php. In the same server and folder as report.php there is a file called report.csv. When report.php is loaded in browser, I want to show one line which will say:
Report.cvs is X minutes old that is all.
If the report is 10 days old, then also I can show the age in minutes. I dont need any complicated X days, Y hours, Z mins etc.
I am worried i might break something in server if I try to add myself since I am not programmer. Is there anyone who can show me what I need to add to report.php to make this work?
Looking through the documentation http://php.net/manual/en/function.fstat.php you might find that filectime ( string $filename ) may be useful.
Now if the file is consistently updated by users you may find that storing the creation/upload time in a Database like SQL/sqlite may be useful.
Ok so basically you need to get the time when the file was last modified, subtract it from the current time, convert the result to minutes and voilĂ .
Here's what that should look like:
$file = ''; // --- Path to the file
$filetime = filemtime($file); // --- File time
$now = time(); // --- Current Time
$fileAge = round(($now - $filetime)/60); // --- Subtract file time from current time, divide by 60 for the minutes and round the result.
echo basename($file).' is '.$fileAge.' minutes old.';
I'm parsing subtitle files (srt format) and here's an example of a line of dialogue:
27
00:01:32,400 --> 00:01:34,300
Maybe they came back
for Chinese food.
The times come in the format
hours:minutes:seconds,milliseconds
I want to manipulate these times and do comparisons but the various PHP classes I've come across don't seem to have support for milliseconds.
My problem:
One thing I want to do is parse 2 subtitle files that are for the same piece of media (e.g. same film, or same TV episode, etc.) and compare each subtitle file's text for the same lines of dialogue. The problem is that the start and end times for the same lines will be slightly off by a few hundred milliseconds. For example, taking the line above, in another subtitle file the time for that same line is
00:01:32,320 --> 00:01:34,160
To get both files' versions of the same line of dialogue, you could check to see if there is a line in file two that is within a few hundred milliseconds of file one's start and end times, and that should catch it. Something like that. So I need to manipulate times by adding milliseconds to them and also do comparisons of those times.
Assuming you're on PHP >=5.3 (required for getTimestamp()), this will work:
$unformatted_start = '00:01:32,400';
$unformatted_end = '00:01:34,300';
// Split into hh:mm:ss and milliseconds
$start_array = explode(',', $unformatted_start);
$end_array = explode(',', $unformatted_end);
// Convert hh:mm:ss to DateTime
$start = new DateTime($start_array[0]);
$end = new DateTime($end_array[0]);
// Convert to time in seconds (PHP >=5.3 only)
$start_in_seconds = $start->getTimestamp();
$end_in_seconds = $end->getTimestamp();
// Convert to milliseconds, then add remaining milliseconds
$start_in_milliseconds = ($start_in_seconds * 1000) + $start_array[1];
$end_in_milliseconds = ($end_in_seconds * 1000) + $end_array[1];
// Calculate absolute value of the difference between start and end
$elapsed = abs($start_in_milliseconds - $end_in_milliseconds);
echo $elapsed; // 1900
Did you try strtotime?
if (strtotime($date1) > strtotime($date2)) { # date1 is after date2
# do work here
}
if (strtotime($date1) < strtotime($date2)) { #date2 is after date1
# do other work here
}
I have a PHP file that randomly generates an image from a folder on every refresh. I downloaded it from here (which also has an explanation).
Instead of randomly choosing images, how can I have it change the image hourly? For example, I would like it have the same image for an hour, and then change when that hour is up. Basically, a new image based on some time interval.
Thanks for the help.
Find line
$imageNumber = time() % count($fileList);
And replace it with
$imageNumber = (date(z) * 24 + date(G)) % count($fileList);
That should work for you.
I'd say you need a random oracle function. Basically, it's a random() function that takes an input and generates a random number, with the guarantee that all calls with the same input will give the same output.
To create the value you pass into the oracle, use something that'll change hourly. I'd use julian_day_number * 24 + hour_number or something of that variety (just hour_number isn't good enough, as it'll repeat itself every 24 hours).
Then, whenever your page loads, generate your hour number, pass it through your oracle, and use the result just like you use your random value now. It'll still appear random, and it'll change once an hour.
Hope that helps!
Edit: Random oracles don't need to be fancy - they can be as simple as (stolen blatantly from this answer to a different question):
int getRand(int val)
{
//Not really random, but no one'll know the difference:
return ((val * 1103515245) + 12345) & 0x7fffffff;
}
Keeping it simple, put 8 different pics in img/ named from 1.jpg to 8.jpg, then:
$imagePath = sprintf("img/%s.jpg", (date('G') %8) +1);
with G param being:
24-hour format of an hour without leading zeros.
Now you are sure that you have a different pic every hour, and everybody sees the same.
EDIT: narrow or widen the repetition period adjusting modulo, 24 has a few divisors [1, 2, 3, 4, 6, 8, 12].
What I'm attempting to do is create a simple "Quote of the Day" script. What this needs to do is be able to read from a simple .txt file, grab each entry per line and output the contents of that line, once per day. For example, if a .txt file had the following text:
This is the quote of the day
This is another quote of the day
This is the last quote of the day
Then, the script would grab the first block of text, This is the quote of the day and output it on the site. It would then cycle through, line by line, based on each incremental day until the end (and then cycle back to the beginning). Hopefully this would just allow people to cut/paste new info in as it would rely on line numbers, not the content itself.
If anyone even knows of a .XML implementation of this - it would be a big help - trying to figure out the simplest way of going about this. Thanks!
Assuming you had a file with 365 lines (one line per the current day)...
$lines = file("quotes.txt");
$day = date("z");
echo $lines[$day];
You can save the current index line and day on the first line of the file, like this:
01;09-11-2011
This is the quote of the day
This is another quote of the day
This is the last quote of the day
To retrieve the quote you would check if the date is today, if it is you get the nth line otherwise you add 1 to the number, update the date and then get the quote.
This should work with any number of lines in your textfile (untested):
// get lines
$lines = file('lines.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
// snap to midnight
$day = mktime(0,0,0, date("n"), date("j"), date("Y")) / (3600*24);
// modulo fun
echo $lines[ $day % count($lines) ];
It's very simple.
1.) You create a text file with 7 lines, each line represents a quote.
2.) PHP: You have to load the file into an array and get the numeric representation of the current day of the week:
$quotes = file('your_file.txt');
$the_quote = $quotes[ date('w') ];
echo $the_quote;
From php.net:
w
Numeric representation of the day of the week
0 (for Sunday) through 6 (for Saturday)
If you want to have a quote for each day in a year, just create a file with 366 lines and use date('z').
The most flexible way is definitely:
$day = date("z");
$file = file('quotes.txt');
$file_length = count($file);
$quote = $file[$day % file_length];
By using the modulus of the day and file length you have a recurring cycle every day from the first line to the last line of the file (and then start again).