Tuesday, August 31, 2021

How to List Files In a Directory in PHP

How to List Files In a Directory in PHP

In this article, we’ll discuss how you can get a list of all the files in a directory in PHP.

In your day-to-day PHP development, you often need to deal with a file system—for example, getting a list of files in a specific directory. PHP provides a few different ways that you can use to read directory contents easily. Today, we’ll go through all these methods along with examples to understand how each one works.

The opendir, readdir and closedir Functions

In this section, we’ll discuss a family of opendir, readdir and closedir functions to see how you can use it to get a list of files in a specific directory.

The opendir function allows you to open up a directory handle, which you can use along with other functions for different operations on the directory. You need to pass a the path to the directory in the first argument of the opendir function. If the directory path is valid, a directory handle resource will be returned.

The readdir function allows you to read a directory. You need to provide a valid directory handle in the first argument of the readdir function, and you can iterate over all the entries and get a list of all files in a directory.

The closedir function allows you to close the directory handle which is opened by the opendir function. It’s a good practice to use the closedir function once you’ve done with your operations on the directory handle (which was initially opened by the opendir function).

Now, let’s see it in action as shown in the following example.

Firstly, we’ve used the opendir function to get the directory handle. Next, we’ve used the readdir function to iterate over the $handle directory handle and store a list of files in the $arrFiles array.

The scandir Function

In this section, we’ll see how you can use the scandir function to get directory contents.

The scandir function is a pretty straightforward way to get a list of files and directories in the specific directory. You just need to pass a directory path which you want to read in the first argument of the scandir function.

Let’s go through the following example to understand how it works.

As you can see, this provides a list of files and directories in a single call! If you just need to get the list of files in a directory, this is a better choice than using opendir, readdir and closedir.

The glob Function

The glob function works similarly to the scandir function with the difference that it allows you to specify a pattern for filtering and matching the files in the directory.

Let’s see how to use the glob function to read all the contents of the specific directory.

As you can see, we’ve passed the * pattern since we want to read all contents. On the other hand, if you want to list only specific type of files, you can do that as well as shown in the following snippet.

in this case, $arrFiles would contain only the names of .txt files.

The dir Function

The options that we’ve discussed so far allow you to read directory contents in a procedural way. In this section, we’ll see how you can use the dir function, which is an object-oriented mechanism for reading a directory.

When you use the dir function, and pass a directory path in the first argument, it returns an instance of the Directory class, which you can use subsequently to read directory contents.

Let’s go through the following example to see how it works exactly.

First, we used the dir function to initialize an instance of the Directory class into the $objDir variable. Next, we used the read method of the Directory class to iterate over all the entries.

The FilesystemIterator Class

In this section, we’ll see how you can use the FilesystemIterator class to read directory contents. The benefit of using the FilesystemIterator class is that you can extend the methods of this class and it also provides a lot of other useful methods that allow you to fetch various information about the files as well.

Let’s go through the following example to understand how it works.

As you can see, it’s really easy to use the FilesystemIterator class and iterate over the entries. In the above example, we’ve used the getFileName method of the FilesystemIterator class to get the file name. However, the FilesystemIterator class also provides several utility methods like getExtension, getSize, getPathname and so on.

So that’s how you can use the FilesystemIterator class to get a list of files in a directory.

Conclusion

Today, we discussed different ways that you can use to list all the files in a directory in PHP. Here's a table to compare each method to help you choose which one is right for you.

Function or Class Notes
opendir, readdir and closedir functions not the simplest or most feature-rich method
scandir function simplest way to read file list
glob function very simple and allows pattern matching
dir function object-oriented version of readdir
FilesystemIterator class can provide other info about files, like size or permissions

Create a WordPress Contact Form

Create a WordPress Contact Form

It doesn't matter if you are running a simple blog or a proper business through your website. Providing a proper channel for communication between you and your clients or visitors benefits everyone. You can do this either via comments, social media accounts or a contact form etc. Each of them have their own advantages and disadvantages.

Contact forms are the way to go in more formal settings or if you need personal information from clients. In this post, you will learn how to create a contact form in WordPress for free. It might take a little time but the benefits make it worth the effort.

Why Do You Need a Contact Form?

Lets begin this discussion by asking another question. Isn't it simpler to just provide some email address and other related contact information on a Contact Us page somewhere on the website? Of course, we can do that but the time you save during the initial setup will be wasted multiple times over when you have to filter out all the spam.

Anyone who has managed a modestly popular website knows that the Internet is filled with spam bots. They keep scraping webpages for any information they can get to post spam. This could include posting shady links in comments or sending emails to whatever email addresses they can lay their hands on while scraping a page.

For you, this basically means getting bombarded with spam emails that can contain potentially harmful links. It could also result in lost revenue if the spam overload prevents your from reading an important email from clients.

Get the Information You Need

Your clients might not always know exactly what information they need to provide in order for you to quickly resolve their issue. When you create your own contact form, you can set it up in a way that clients or visitors who fill it up provide all the necessary information.

Show Them Additional Resources

Once the users have filled out a contact form, you can show them additional information based on their input in the contact form. This can include things like expected response times, help articles or other ways to contact you.

How to Create a WordPress Contact Form?

WordPress has a robust plugins-based ecosystem which gives you a huge variety of options when it comes to setting up a contact form. In this tutorial, we will use a free plugin to create our contact form.

Go to Plugins > Add New inside you WordPress Admin dashboard and then search for Contact Form. This will show you a bunch of plugins. Read their reviews and features to see which one would be ideal for you now and in the near future.

Contact Forms in WordPress Plugins DirectoryContact Forms in WordPress Plugins DirectoryContact Forms in WordPress Plugins Directory

For our tutorial, we will use the Forminator Plugin which allows you to create a bunch of other forms in the future if need arises. The first step is to Install and Activate the plugin.

After that, you should navigate to Forminator > Dashboard and then click on the Create button under the Forms section.

Forminator Dashboard Create FormForminator Dashboard Create FormForminator Dashboard Create Form

The plugin comes with a bunch of basic templates for common types of forms. We will just select Contact Us and then click Continue.

Forminator Contact Us FormForminator Contact Us FormForminator Contact Us Form

Specify a name for the contact form the make it easier to identify for you later, in case you decide to create a bunch of other forms.

Forminator Contact Form NameForminator Contact Form NameForminator Contact Form Name

You will see that there are some already-added fields on the next screen which include First Name, Email Address, Phone Number and Message. The asterisk beside First Name and Email Address means that they have been marked as required.

Forminator Pre-Added Contact Form FieldsForminator Pre-Added Contact Form FieldsForminator Pre-Added Contact Form Fields

You can click on the Insert Fields button to add other fields to the form. We have added a Select dropdown for choosing a department that will handle this submission and an Input field to specify the account number for easy identification in our case. Click on Settings for the Select dropdown field to make filling it out a requirement.

Forminator Select Dropdown RequiredForminator Select Dropdown RequiredForminator Select Dropdown Required

Edit the label of the of the dropdown to read Choose Department and provide a list of departments for people to select.

Forminator Select OptionsForminator Select OptionsForminator Select Options

Finally, click Apply to apply all these settings to our dropdown.

Forminator Apply SettingsForminator Apply SettingsForminator Apply Settings

You can always check what your form will look like by clicking on the Preview button before actually publishing it.

Forminator Preview and PublishForminator Preview and PublishForminator Preview and Publish

Click on the Publish button and you will see a shortcode. Place the shortcode wherever you want the contact form to appear.

Forminator Published Form ShortcodeForminator Published Form ShortcodeForminator Published Form Shortcode

For this tutorial, I have placed it on the contact us page and it looks like the image below.

Forminator Published Contact FormForminator Published Contact FormForminator Published Contact Form

The plugin also gives you to option to add a Google reCAPTCHA to the form to counter spam submissions. It is easy to integrate once you get your keys and secret from Google.

As you might have noticed the contact form itself comes with very minimal styling so that it blends in easily with the rest of the website design. There are four different styles under Appearance tab to choose from and they all provide minimal styling while giving a unique look at the same time. You can even tell the plugin to get rid of all the styling and use the CSS in the website's theme to style it.

Customizing the Form Submission Behavior

It is a good practice to give users some kind of acknowledgement that you have received their submission after they click the Send Message button. Almost all contact form plugins will have some settings that you can configure to either redirect users to some other page after a successful submission or show them a custom message.

Forminator gives you the option to customize form submission behavior by visiting Forminator > Forms from the WordPress admin dashboard. Select the form whose behavior you want to modify and then go to the Behavior tab. In our example, we simply tell the users that we appreciate their submission and will get back to them within 48 hours.

Form Submission BheaviorForm Submission BheaviorForm Submission Bheavior

Final Thoughts

Our goal in this tutorial was to show you how to create a contact form for your WordPress website with minimal effort. We began the post by explaining why you should add a contact form to your website instead of simply placing your contact information on a webpage. After that, we moved on to discuss how we can use free plugins to create a basic WordPress Contact form.

Hopefully, you should now have a basic contact form that can show you information submitted by users. Eventually, you will be able to create more complicated contact forms that give you granular control over the flow of users and information from one step to the next.

To learn more about the options for creating contact forms in WordPress, including some tips on some of the best premium contact form and best form builder WordPress plugins available, check out some of our other posts here on Envato Tuts+.