Automatically creating next and previous type pages using glob - php

Trying to make it so that the glob function displays only the first 10 results (text files from a folder) and then automatically the next 10 with a next button.
Currently, I used array_slice to display only the first 10, but I'm not sure how to automate the process.
foreach(array_slice(glob("*.txt"),0,9) as $filename) {
include($filename); }
Oh and while I'm at it, if possible, display something like "displaying 1-10" and last/first links. I could probably figure that out myself after I get past the first obstacle, so don't bother with this unless it's a super easy solution.

What you're trying to accomplish is called pagination. From your example, you can dynamically choose which ten you're viewing by setting a variable that determines what number (file) to start at.
Example:
<?php
$start = isset( $_GET['start']) ? intval( $_GET['start']) : 0;
$glob_result = glob("*.txt");
$num_results = count( $glob_result);
// Check to make sure the $start value makes sense
if( $start > $num_results)
{
$start = 0;
}
foreach( array_slice( $glob_result, $start, 9) as $filename)
{
include( $filename); // Warning!
}
If you only want to do increments of 10, you can add a check to make sure $start is divisible by 10, something like this after $start is retrieved from the $_GET array:
$start = ( $start % 10 == 0) ? $start : 0;
Now, for links, all you need to do is output <a> tags that have the start parameter set correctly. You will have to do some logic to calculate the next and previous values correctly, but here is a simple example:
$new_start = $start + 10;
echo 'Next';
Edit: As the comments above suggest, you probably do not want to include() these files, as include() will attempt to interpret these files as PHP scripts. If you just need to get the contents of the text files, use file_get_contents instead.

Related

How to run php file for only 10 times a day without cron?

I am new to php so please mind if it easy question. I have a php script, I want it to be executed only 10 times a day and not more than that. I don't want to use cron for this. Is there any way to do this in php only?
Right now I have set a counter which increases by one every time any one runs the script and loop it to 10 times only. if it exceeds it it shows an error message.
function limit_run_times(){
$counter = 1;
$file = 'counter.txt';
if(file_exists($file)){
$counter += file_get_contents($file);
}
file_put_contents($file,$counter);
if($counter > 11 ){
die("limit is exceeded!");
}
}
I want some efficient way to do this so everyday the script is only executed for 10 times and this is applicable for everyday i.e this counter gets refreshed to 0 everyday or is there any other efficient method.
I would rather recommend that you use a database instead - its cleaner and more simple to maintain.
However, it is achievable with file-handling as well. The file will be of format 2019-05-15 1 (separated by tab, \t). Fetch the contents of the file and split the values by explode(). Then do your comparisons and checks, and return values accordingly.
function limit_run_times() {
// Variable declarations
$fileName = 'my_log.txt';
$dailyLimit = 10;
$content = file_get_contents($fileName);
$parts = explode("\t", $content);
$date = $parts[0];
$counter = $parts[1] + 1;
// Check the counter - if its higher than 10 on this date, return false
if ($counter > $dailyLimit && date("Y-m-d") === $date) {
die("Daily executing limit ($dailyLimit) exceeded! Please try again tomorrow.");
}
// We only get here if the count is $dailyLimit or less
// Check if the date is today, if so increment the counter by 1
// Else set the new date and reset the counter to 1 (as it is executed now)
if (date("Y-m-d") !== $date) {
$counter = 1;
$date = date("Y-m-d");
}
file_put_contents($fileName, $date."\t".$counter);
return true;
}

How can you determine remaining space on page with ezpdf?

I'm using rospdf/php-pdf - the middle of the pdf is a table of variable length. I want to make sure there is enough space to print the final section on the page, if not I want to add a new page. I'd like to do something like this but $position has no value. How can I find out the current position?
$position = $pdf->ezSetDy;
if($position < 100){
$pdf->ezNewPage();
}
You can try the following:
$yPos = $pdf->y - $pdf->ez['bottomMargin'];
if ($yPos < 100) {
$pdf->ezNewPage();
}

PHP foreach -function-and calling a function for every 10 keys in the list

My code is:
$count=0;
foreach( $List AS $email){
$data = my_function($url);
$count++;
if(filter_var($email , FILTER_VALIDATE_EMAIL)){
...............
my_function runs a simple cURL for an url and returns session_id and api_identity as results. If I run it in the loop for each email in the list, my code is very slow and takes time to show results.
now
$data = my_function($url);
Is applied for each email.
My question:
Is there any way to apply $data = my_function($url); for every 10th mail in the whole list?
If I'm not misunderstanding your question, you want to do something every nth iteration, which can be accomplished using modulo operators:
$count = 1;
foreach ($List as $email)
{
if ($count % 10 == 0) $data = my_function($url);
$count++;
...
}
If you don't know what x % y does, it simply returns the remainder of the expression x/y. A simple trick is therefore to use the fact that when evaluating x % n for different values x = 1, 2, 3..., the same result will repeat every nth time.
Note that depending on what your counter starts at, you will get a different start-email. If you keep it 0 as you have now, the function will be called for the 1st, 11th, 21st, .... emails. If you change it to 1 as I did, the first email for which the function will be called is the 10th one.
You can use https://stackoverflow.com/a/44883380/7095134 this answer or by using counter variable you can achieve that.
e.g:
counter=0;
for(i=0; i<=100; i++)
{
if(counter==10){ counter=0; call_your_function(); }
else { do the rest of work; counter++ ;}
}

How to read filenames containing a number and only use those with less than or equal to a specified value, also how to make my 'cache' more efficient?

So I've got a couple of questions that I'm hoping someone will be able to help me with.
Firstly, I'm trying to create a page which parses information and organizes it by the hour into a table. At the moment my script parses the information with Simple HTML Dom and creates a text file for each hour called "hour_%time%.txt" (e.g. hour_02.txt, hour_14.txt, hour_22.txt). Each file will contain the parsed information as a table row.
How would I go about only using the files with times earlier than the current hour, so if the current hour was 9am, only files ending with equal to or less than 09 would be used? I was trying to use either explode or preg_match but I couldn't get it to work.
My code at the moment looks like so:
date_default_timezone_set('UTC');
$currentHour = date('H');
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
$files = glob("cache/hour_*.txt");
foreach($files as $txt){
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
echo '</table></tbody>';
And secondly, I'm fully aware this isn't the best way to do this but I couldn't figure out a better way myself. Can anyone suggest a more efficient way to store the parsed data and access it? Is it possible to use a single file? I did consider appending the same file however as my page will update frequently it ended up adding multiple lines of data for the same hour. Each file contains a string like so:
<tr><td>10:00</td><td>21</td><td>58</td><td>4</td><td>43</td></tr>
Any help is appreciated.
First convert your String of the hour to a number
[PHP]
$currentHour = intval($currentHour);
next compare
if($currentHour <= 9){ // < for less and <= for less and equal
doStuff
}
This only will display the file of the exact hour. Tell me if doesn't work for edit it.
date_default_timezone_set('UTC');
$currentHour = intval(date('H'));
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
$files = glob("cache/hour_*.txt");
if($currentHour == $currentHour){
foreach($files as $txt){
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
}
echo '</table></tbody>';
I ended up creating a variable called $globSearch and used if/elseif to create a search string based on the current hour. My code now looks like this:
date_default_timezone_set('UTC');
$currentDate = date('d/m/Y');
$currentHour = intval(date('H'));
$cache_file = 'cache/hour_'.$currentHour.'.txt';
$data = '<tr><td>'.date('H:00').'</td><td>'.$firmato_count.'</td><td>'.$inviato_count.'</td><td>'.$positive_count.'</td><td>'.$negative_count.'</td></tr>';
file_put_contents($cache_file, $data);
echo '<table class="table"><tbody>';
echo '<tr><th>Time</th><th>Firmato</th><th>Inviato</th><th>Positive</th><th>Negative</th></tr>';
if ($currentHour <= 9) {
$globSearch = "{cache/hour_[0][0-".$currentHour."].txt}";
} elseif ($currentHour >= 10 && $currentHour <= 19) {
$splitInt = str_split($currentHour);
$globSearch = "{cache/hour_[0][0-9].txt,cache/hour_[1][0-".$splitInt[1]."].txt}";
} elseif ($currentHour >= 20 && $currentHout <= 23) {
$splitInt = str_split($currentHour);
$globSearch = "{cache/hour_[0][0-9].txt,cache/hour_[1][0-9][2-".$splitInt[1]."].txt}";
}
//$files = glob("{cache/hour_[0][0-9].txt,cache/hour_[1][0-3].txt}", GLOB_BRACE);
$files = glob($globSearch, GLOB_BRACE);
foreach ($files as $txt) {
$hourlyfile = file_get_contents($txt);
echo $hourlyfile;
}
echo '</table></tbody>';
Thanks for replying Ruben and COOLGAMETUBE, much appreciated.

Retrieve one element 1 time per 10 page reload

I have an array with 10 elements.
$arr = range(0, 9);
I want to retrieve one element one time per 10 page reload.
Ho can I do this?
With session variables and a bit of modular arithmetic, you should get the job done
<?php
session_start();
$array = range(0, 9); // this could be any array
$repeat = 10;
if(!isset($_SESSION['counter'])) $_SESSION['counter'] = 0;
if(!isset($_SESSION['subcounter'])) $_SESSION['subcounter'] = 0;
echo $array[$_SESSION['subcounter'] % sizeof($array)];
if($_SESSION['counter'] % $repeat == 0)
$_SESSION['subcounter']++;
$_SESSION['counter']++;
?>
Use cookies instead of sessions if you want to keep your counter after the browser closes.
code tested and approved
Try this:
$arr = range(0,9);
$random = array_rand($arr, 1);
echo $random;
This will pick one element inside the range of your array of $arr for every reload.
For you to truly get it to happen once every x times, the server will have to be aware of when the last time it retrieved an element was, as well as how many page refreshes have happened since. You should use a database to retain this info, and reference the DB on each page load to know whether to retrieve an element.
Good luck!
This code will start a user session, and keep count of how many request have been performed, it will then re-generate the array index.
If however you need to slowly exhaust this list, you'll need to keep track of what index's you've assigned to the user, or perform this return incrementally.
session_start();
$arr = array('Item A','Item B','Item C','Item D','Item E','Item F','Item A','Item H','Item I','Item J');
if( isset($_SESSION['counter'],$_SESSION['showthisindex']) === false or $_SESSION['counter'] >= 10 )
{
$_SESSION['counter'] = 1;
$_SESSION['showthisindex'] = array_rand($arr);
}
else
{
$_SESSION['counter']++;
}
echo $arr[ $_SESSION['showthisindex'] ];

Categories