Can the glob function in PHP accept a series of values as a range?

Currently, I have a significant amount of files stored within a specific directory, and to locate particular files using PHP's glob function. Below is the code snippet that I am currently using:

/* SAMPLE FILE NAME: PR330037JED10220161204.csv */
$dir        = 'Files/Payment/';
$prefix     = 'PR';
$vendorNo   = '330037';
$region     = 'JED';
$date       = '20161204';
$files      = glob($dir.$prefix.$vendorNo.$region."*".$date.".csv");

Although this code functions as intended, I am interested in modifying it to check whether the date component falls within a specified range. What adjustments can be made to the glob expression to achieve this functionality?

Answer №1

Iterate through the date range using the code snippet below:

$dir        = 'Files/Payment/';
$prefix     = 'PR';
$vendorNo   = '330037';
$region     = 'JED';

$begin = new DateTime( '2016-12-05' );
$end = new DateTime( '2016-12-10' );

for($i = $begin; $begin <= $end; $i->modify('+1 day')) {
    $date = $i->format("Ymd");
    $files = glob($dir.$prefix.$vendorNo.$region."*".$date.".csv");
}

Answer №2

A useful method to consider is using the GLOB_BRACE FLAG, which is supported by the glob() function.

For instance:

<?php

$directory   = 'Files/Payment/';
$prefix      = 'PR';
$vendorNumber= '330037';
$region      = 'JED';
$date        = '20161204';

$date1 = new DateTime();
$date2 = new DateTime('-1 day');
$date3 = new DateTime('-1 week');
// Include your desired dates here or find a way to automate generating this list based on your requirements
$daysList = $date1->format('Ymd').','.$date2->format('Ymd').','.$date3->format('Ymd');

$pattern    = $directory.$prefix.$vendorNumber.$region."*"."{".$daysList."}".".csv";

$matchingFiles = glob($pattern, GLOB_BRACE);

Answer №3

glob() does not offer support for ranges. To work around this limitation, you can utilize the GLOB_BRACE option in glob to list dates:

$date = '{20161204,20161205,20161206}';
$pattern  = sprintf('%s/%s%s%s*%s.csv',
  $dir, $prefix, $vendorNo, $region, $date);

$files = glob($pattern, GLOB_BRACE);

A more adaptable approach involves iterating through the directory, extracting dates from filenames, and checking if they fall within a specified date range:

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

$date_from = 20161204;
$date_to   = 20161206;

$pattern  = '/^' . preg_quote($prefix . $vendorNo . $region, '/') .
  '.*(?P<date>\d{8})\.csv$/';

$it->rewind();
while ($it->valid()) {
  if (!$it->isDot()) {
    $path = $it->key();
    $basename = basename($path);
    if (preg_match($pattern, $basename, $matches) &&
      isset($matches['date']) &&
      $matches['date'] >= $date_from &&
      $matches['date'] <= $date_to)
    {
      echo $basename, PHP_EOL;
    }
  }

  $it->next();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The JavaScript function you are trying to use is not defined

Hi there, I'm new to javascript and angularjs. I've created a function in my controller to open a website when clicking on a button. However, I'm encountering an error message saying ReferenceError: openWebsite is not defined when trying to ...

Fluctuating updated site (ajax)

What method do you recommend for maintaining the data in a table on a page current? Currently, I am using a timer that connects to the server via ajax every 2 seconds to check for updates. Is there a way to trigger an event or function only when the cont ...

What is the best way to extract values from a JavaScript function?

As someone who is new to Javascript, I am interested in learning how to retrieve values from a function. In the given code snippet, my goal is to extract TheName, TheHeight, TheGender, and TheSexuality when executing the function so that I can utilize the ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Since switching to PHP 5.5 from version 3.x, I have noticed that it is attempting to interpret my JavaScript comment within a script tag in a PHP include file

After a long break from working with PHP, I recently encountered an issue with an older website I built using PHP and the include function. The site was functioning perfectly until the web host updated PHP to version 5.5, causing a strange bug where it see ...

Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format no ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

Retrieving Information from Ajax Response Following a Successful Insert Query in Codeigniter

I am trying to use ajax method to insert form data into a database and then redirect it to the next page. I have successfully passed the data in ajax and inserted it into the database table. However, I am facing an issue with getting the generated referenc ...

Melodic Streaming Platform

I currently have a client-side application built using React. I have a collection of music stored on my Google Drive that I would like to stream online continuously. I lack experience in server-side programming. Can you suggest any resources or steps I s ...

What is the best way to utilize an array that has been generated using a function?

After creating a customized function that generates an array of numbers, I encountered an issue where the array is not accessible outside the function itself. function customArrayGenerator (length, order){ // length = array length; order = integer order o ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

Is there a way to call a Vue function from an onclick event in JavaScript?

Creating a vue component and trying to call a function defined in Vue methods using the onClick attribute when modifying innerHTML is resulting in an error message stating "showModal is not defined". Here is the showModal function where I'm simply try ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...

Tips on saving every query outcome in a separate array and delivering it back to the controller upon completion

I am currently facing an issue where I receive data in a function from my controller, and inside my model function, I need to retrieve results using a query with a dynamic value of channel. The channel ID will be coming from each checkbox on my HTML view ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

Steps to create a custom function that can manage numerous onclick actions to toggle the visibility of a specific field

I'm relatively new to coding and JavaScript. I'm working on a basic webpage that involves showing and hiding parts of sentences for language learning purposes. Is there a way to create a single function that can show and hide the sentence when a ...

Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter. I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying ...

"Displaying a popup message prompting users to refresh the page after clicking

I need to implement a feature where the page refreshes only after the user clicks the "OK" button on a dialog box that appears once a process is completed. The issue I'm facing is that in my current code, the page refreshes immediately after the proc ...

Deleting an element from HTML using jQuery

In the midst of creating a system that allows users to construct their own navigation structure, I have encountered a stumbling block. The idea is that when a user lands on the site, they are presented with a list of available topics from which they can ch ...