Jump to content

SORT directory of folder


phppup

Recommended Posts

I have a PHP script that reads the image files in a folder and displays them for viewing.

When originally tested with three images, it seemed to be displaying them in alphabetical order by name (as desired).

Now, with more image files added, it is displaying the pictures in a seemingly random order.  Can I use a SORT command similar to the method for organizing data from a database in my script (to organize the files by name)?

Link to comment
Share on other sites

The heart of the script is here

    $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;
                if (is_readable($path)) {
                    if (is_dir($path)) {
                        return scanDirectoryImages($path, $exts);

Yet none of my SORT commands have altered the (seemingly) random selection of images.

What sort command and placement would be recommended?

Link to comment
Share on other sites

Did you try out glob(), as requinix suggested? I haven't used the function myself, but it appears to have a built-in sorting feature. More information, including examples, can be found here:
https://www.php.net/manual/en/function.glob.php

Alternatively, you could store all the file names as an array. Then using something like sort() to alphabetize them.

Link to comment
Share on other sites

I've been plugging glob() EVERYWHERE, but do not seem to be getting a satisfactory result of sorting my images.

Am I doing something wrong?  Or is a recursive script incapable of sorting?

A solution would be wonderful.

Thanks

Edited by phppup
Link to comment
Share on other sites

There is no updated code.

All my efforts failed by either causing the gallery to display in its arbitrary order.  Otherwise, it eliminated the display entirely because the code was faulty.

I thought that   glob($directory);   was the correct utilization of the command either in conjunction with or before assembling the $directoryList.

Again, my efforts seem to be missing the mark, so if you have a viable answer, please let me know.

 

Link to comment
Share on other sites

18 hours ago, phppup said:

I thought that   glob($directory);   was the correct utilization of the command either in conjunction with or before assembling the $directoryList.

Why would you think that? As previously stated in this thread:

On 12/6/2019 at 2:34 PM, cyberRobot said:

The following link provides a seemingly better example of targeting a directory with glob():
https://www.electrictoolbox.com/php-glob-find-files/

Note that the first argument of glob() expects a pattern.

The manually explicitly states this as well. It doesn't state a path/directory name - it states a pattern. If you look at any of the examples either in the manual or the ones linked to by others, you would see that it takes more than just the path to the directory. Heck, @cyberRobot asked you to provide the value of the variable $directory so we could help, but you refused and are simply wanting us to do it for you. readdir() is designed to return all the contents of a directory - so it only needs a pointer to the directory. glob() is designed to return a filtered list of a directory's contents and therefore needs something more than just the path to the directory. Regular expressions (i.e. the pattern) is one of the more difficult areas of programming (IMO), so it would be understandable if you were to ask about how to write the expression. But, instead you just put what you "think" it should be and don't respond to direct questions.

I think you are taking the responses as people not being helpful. What I see are people that are trying to get you to think deliberately and analytically in order to find answers for yourself. Or to at least get a sense of the problem so you can ask the right questions. I for one am more likely to help someone who can demonstrate through their questions/responses that they've done some research into their problem rather than just throwing code at the wall to see what will stick.

Having said all that (which will probably be forgotten by the next post), I will throw you a bone. The '*' character is a 'character class' that matches anything. The link  @cyberRobot posted had this example:

$files = glob("/path/to/directory/*.txt");

Which will " . . . find all the files in the directory /path/to/directory with a .txt file extension" because the '*' would match any number of characters after the path name and before the '.txt'. So, what would happen if you removed the '.txt' from that pattern? It would match anything that comes after the directory path (i.e. any files/folders). However, since you are looking for images, why not use the later example on that page which was specifically built to only return images?

Link to comment
Share on other sites

Quote

provide the value of the variable $directory so we could help

echo scanDirectoryImages("uploaded");  is ahead of the function that I provided above.  It is a recursive function, so it gets called repeatedly inside the script.  I have tried

echo scanDirectoryImages(glob("uploaded/*.*"));

and completely lost the gallery.

Quote

I think you are taking the responses as people not being helpful.

I understand that nobody wants to write my script for me, and I am trying NOT to

Quote

just throwing code at the wall to see what will stick

and therefore I am making efforts that seem logical to me. 

Quote

I will throw you a bone

I appreciate that, but honestly, I have checked every link provided and many more on my own.  I have tried renaming the $path, and nesting the glob() in every area of my script.  Ultimately, as previously mentioned, I either get no affect or I lose the gallery entirely.

It's not for lack of trying, but we all know that a misplaced slash, comma, or quote will prevent me from obtaining success.  Evidently there is something that I am not seeing.  Or something i expect to work that isn't. 

Perhaps the other pertinent question should be, why would the display (that tested well with three images) suddenly sort randomly?

I just want these photos to run or order.

Or maybe reverse order.

But I suppose I should resolve one problem before moving to the next.

PS: sometimes seeing the answer creates a cascade that eliminates the need for postings on similar issues because the learning process takes root.

 

Link to comment
Share on other sites

22 minutes ago, phppup said:

Perhaps the other pertinent question should be, why would the display (that tested well with three images) suddenly sort randomly?

Yeah, that's a mystery isn't it. It's not like it is explained in the manual on the first sentence of the description for the readdir() function, right? Nope, you have to read all the way to the second sentence .

Quote

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

You probably created those first three files such that they happened to be created in alphabetical order. The fact that it is right there plain as day in the manual for that function would lead someone to believe you never took the time to do even a cursory look at the manual. I had no idea of how readdir() determined the order in which it returned files, and it took me all of 5 seconds to find out without any special skills/knowledge required to do so. It leaves one wondering what level of effort was put into understanding the glob() function before just randomly trying things without even understanding what the problem is "I have tried renaming the $path, and nesting the glob() in every area of my script." Did you have a reason to believe the path was wrong or that glob() should go somewhere else in the script?

When using a function for the first time, if I have any problems I will almost always create a test script. I will start with an example from the manual or a tutorial, verify it works and then figure out how it needs to be modified for my use. I have a very good idea of what your problem is, but I'm reticent to give you the solution because you are wasting our time and yours with how you are currently approaching the problem. And, I'm certain you will be back time and again with 'simple' problems that end up taking significant time to resolve. You need to learn how to problem solve.

Start with this code and see what the results are. Then start making (small) changes until it is returning the results you want. E.g. I'd start by changing it to get to the intended directory. Then I would change it to only return the files I was interested in. If you want further help from me, please provide details on what you tried up till you got stuck.

$globFiles = glob('*');
echo "<pre>" . print_r($globFiles, 1) . "</pre>";

 

Link to comment
Share on other sites

Yup, I admit it (as if you needed my guilty plea), I never read up on readdir().  It worked in a tutorial and it just kept on working. 

I will try to get this problem SORTED out (see what I did there? LOL), but please keep in mind that I chose my username intentionally (as I do not work with coffee as readily as you and many others here).

You may have chosen your username with equal intent (not entirely sure yet. *wink*)

Link to comment
Share on other sites

I think the essentials of my code are 

echo scanDirectoryImages("uploaded");

    $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;

Does glob() need to go directly with the "uploaded/*.*" in the first line ECHO?

It fails there.

Since the $directoryList comes from $directory does it needed to be effective there? on which? On either?

The $path contains data from $directory AND $file, but isn't this too far down in the process to intiate glob()?

Link to comment
Share on other sites

So, you didn't follow my advise to start with a simple test script to see what glob() is returning and then go from there? Instead, you're back still trying to shoehorn it into your current code without understanding what it is doing. It seems you don't even understand what your current code is doing. You need to stop the trial and error approach to coding and actually learn what the functions do. You're being lazy in a way that is causing you more work.

Link to comment
Share on other sites

I am trying to get THIS code to SORT so I can use it this weekend.

I do not have the time now to re-write it or play with testing (for learning purposes).

Seeing the actual answer and how it works will likely be very helpful.  I can then review the manual and these posts and fine tune and re-write with a more educated approach, but for now, finding a working solution is the priority.

Link to comment
Share on other sites

No you don't want to take the time to actually learn anything and just want us to provide solutions. If you had simply done a quick test using glob() I'm confident you would have already had a solution and moved on. Instead, we've wasted quite bit of time in this thread and you are probably further from a solution because you are getting lost in assumptions and trial & error attempts. That must be really frustrating for you. I've already resigned myself that I am not going to give you the solution. You have to earn it. You were right that the part you need to change was within those four lines you posted earlier. But, you can't just replace using the glob() function and expected it to work. If you had just a basic understanding of what those four lines do and what glob() does it is a very simple solution.

This will be my final attempt to help you unless you can demonstrate that you are at least putting in some (worthwhile) effort.

Here is what you have

    $directoryList = opendir($directory);
        while($file = readdir($directoryList)) {
            if ($file != '.' && $file != '..') {
                $path = $directory . '/' . $file;

If you were to put comments in your code you may have figured it out already. Since you didn't let's review what that code does:

1. The first line creates a "handle" to the directory (think of it like making a connection to a database). So, the variable $directoryList is misnamed because it isn't a list.
2. Here you have a while list that will continue as long as a new record can be assigned to $file from the readdir() function. That function returns each record name found in the file handler created above
3. The if() statement ensures that the default filesystem objects of the current and parent directories are not included in the processing
4. This defines (I assume) the fill path to the file.

So, what does glob() do? It returns an array of files based on an expression. So, obviously your looping logic needs to change since you wouldn't use a while() loop to iterate over an array. Typically you want a foreach() loop, correct? A foreach() loop will return the value of each element in the array. But, how do you get the correct values in the array? Well, you could just throw random data into the glob() function and scratch your head when things don't work. Or, you could take the two line test script I provided and modify the pattern to verify you are getting the right values before you try using it in a foreach() loop of your current logic. FYI: glob() does not return '.' and '..', so the if() condition will be unnecessary.

Good luck

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.