Please wait

File Functions

The filesystem is a way that an operating system organizes and stores files and directories on a storage device, like a hard drive or SSD. It's like a big filing cabinet for your computer where everything is neatly arranged in drawers (directories) and folders (subdirectories), each with a specific label (filename).

When we talk about interacting with the filesystem in programming, we're talking about using code to do things like read, write, delete, or check files and directories, just like you would manually do by clicking around on your computer. It's a fundamental aspect of working with data on computers and enables applications to store information between sessions, share data between users, and more.

Interacting with files in PHP essentially means performing various actions on files and directories stored on your server. You can read, write, delete, and check files. Directories can also be managed with PHP.

These actions allow you to store, manage, and retrieve data on your server, making your website more dynamic and interactive.

Magic Constants

Before exploring these functions, we should talk about magic constants. Magic constants in PHP are special constants that change their value depending on where they are used. They start with a double underscore (__) and are written in uppercase. These constants provide information about the code, such as file paths, function names, and line numbers.

For this lesson, there are two magic constants you'll find super useful. The __FILE__ and __DIR__ constants in PHP are two specific magic constants that provide information about the file and directory where they are used.

  • The __FILE__ constant returns the full path and the name of the file where it's used. It can help in debugging by identifying exactly where in your file structure a piece of code is located. It's also handy for including or requiring other files relative to the current file's location, ensuring that the paths work regardless of the current working directory.
  • The __DIR__ constant returns the full directory path of the file where it's used. Similar to __FILE__, it's helpful for working with paths within your application. If you need to reference other files or directories relative to the current file's directory, __DIR__ gives you a reliable starting point.

You can output these constants like so:

echo __FILE__ . "<br>";
echo __DIR__;

Checking a File Exists

Before working with files, you may want to check if a file exists. If you try to read or manipulate a file that doesn't exist, it can cause an error in your program. By checking if a file exists first, you can handle the situation gracefully. For example, you might create a new file if it doesn't exist or update it if it does.

You can check if a file exists by using the file_exists() function. This function takes the path to the file as a parameter and returns true if the file exists and false otherwise.

if (file_exists('example.txt')) {
  echo 'The file exists!';
} else {
  echo 'The file does not exist.';

In this example, we're using the file_exists() function with a file called "example.txt". If it does exist, we'll echo 'The file exists!'. Otherwise, the user will see 'The file does not exist.'.

Directories can be passed in

The file_exists() function can be used to verify a directory exists. You don't always have to pass in a filename.

Verifying Files Only

Since the file_exists() function can check if a directory exists, you may be solely interested in verifying files.

The is_file() function in PHP is used to determine if a specific path points to a regular file, as opposed to a directory or something else. It returns true if the path specifies a regular file and false otherwise.

if (is_file('example.txt')) {
  echo 'This is a regular file!';
} else {
  echo 'This is not a regular file.';

Difference Between is_file() and file_exists()

  • file_exists(): This function checks if a file or a directory exists at the given path. It doesn't differentiate between a regular file, a directory, or other types of file-like entities.
  • is_file(): This function goes a step further and checks if the given path points to a regular file, not a directory or anything else.

So, while file_exists() can tell you if something is present at a given path, is_file() can tell you if that something is specifically a regular file. Both functions are handy, but is_file() provides a more specific check, suitable when you need to ensure that the path you're working with points to an actual file.

File Permissions

If a file exists, the next thing you would want to do is check for the file permission. File permissions are a set of rules that determine who can read, write, or execute a file on a computer system. Think of them like locks and keys for your files and folders. These are the types of file permissions:

  • Read (R): Determines who can open and read the file.
  • Write (W): Determines who can modify the file.
  • Execute (X): Determines who can run the file as a program.

By setting the right permissions, you can keep your files safe. For example, you might want to make sure that only you can change or delete your personal files so nobody else messes with them. You can use permissions to control who can see your files. If you have private or sensitive information, you can set permissions to make sure that only specific people (or no one at all) can read those files.

On a more technical level, some files are essential for your computer to work correctly. The wrong changes to these files could cause problems, so the permissions are set to prevent unauthorized changes.

File permissions are like the rules in a library. Some books are available for anyone to read, some can only be read inside the library, and some are in a special section where only certain people can go. Setting these rules properly helps keep everything organized and protects the important and private stuff. It's a crucial concept in managing files and keeping them secure.

Checking for Readability

In PHP, you can check if a file is readable by using the is_readable() function. This function takes the path to the file as a parameter and returns true if the file is readable and false otherwise.

if (is_readable('example.txt')) {
  echo 'The file is readable!';
} else {
  echo 'The file is not readable.';

This check can be important in scenarios where you want to read a file but aren't sure if the permissions allow for it. By using is_readable(), you can prevent errors and handle the situation gracefully, perhaps by showing a user-friendly error message if the file can't be read.

Checking for Writability

You can check if a file is writable by using the is_writable() function. This function takes the path to the file as a parameter and returns true if the file is writable and false otherwise.

if (is_writable('example.txt')) {
  echo 'The file is writable!';
} else {
  echo 'The file is not writable.';

This function checks the file's permissions to determine whether the current user or process has written access to the file. It's a valuable check to perform before attempting to modify a file, as it allows you to handle the situation appropriately if the file is not writable, such as informing the user or taking an alternative action.

Grabbing the File Size

Grabbing the file size is a common task you'll want to perform to perform validation. Users are able to upload files, but you may want to limit the file upload size, so you'll need to grab the file size.

Files are measured in bytes. A byte is like a tiny container that can hold a small amount of information. Imagine your computer's storage as a huge wall of tiny drawers, and each drawer can hold a tiny piece of information. Each of those drawers is like a byte.

In technical terms, a byte is made up of 8 bits, and each bit is a single binary value - either 0 or 1. You can think of those 8 bits as a series of 8 switches, each being either on or off. The different combinations of on/off can represent different characters or values.

You can use the filesize() function to get the size of a file. You just provide the path to the file, and it returns the size in bytes. Here's a basic example:

$size = filesize('example.txt');
echo "The file size is $size bytes.";

Grabbing the Content Type

The mime_content_type() function in PHP is a simpler way to determine the MIME type of a file. It's straightforward to use and takes the file's path as its argument, returning the MIME type as a string.

$filename = 'example.jpg';
$mime_type = mime_content_type($filename);
echo "The MIME type of the file is " . $mime_type; // Outputs something like "The MIME type of the file is image/jpeg"

This function is useful when you want to quickly check the MIME type. It's particularly handy for validating file uploads, determining how to process a file, or setting appropriate headers when serving files over the web.

Extracting the File Path

If you have a full path of a file, you might want to break it apart. In this case, you can use the pathinfo() function. The pathinfo() function in PHP is used to get information about a path. It returns an array containing details about the file path that you can use for various purposes. You can extract the following pieces of information from it:

  • dirname: The directory path without the filename.
  • basename: The complete filename with its extension.
  • extension: The file extension (without the leading dot).
  • filename: The filename without the directory path or extension.

Here's how you can use it:

$path = 'folder/subfolder/example.txt';
$info = pathinfo($path);
$directory = $info['dirname'];    // Outputs 'folder/subfolder'
$filenameWithExtension = $info['basename']; // Outputs 'example.txt'
$extension = $info['extension'];  // Outputs 'txt'
$filename = $info['filename'];    // Outputs 'example'

You can also pass a second argument to get just one piece of information. For example, if you only want the extension, you can use:

$extension = pathinfo($path, PATHINFO_EXTENSION); // Outputs 'txt'

Key Takeaways

  • Be aware of file permissions to ensure that files are accessible, writable, or executable only by the intended users or processes.
  • Learn how to get information about files, such as their size, type (MIME type), and path components (using functions like filesize(), mime_content_type(), and pathinfo()).
  • Use functions like file_exists() and is_file(), to check whether a file or directory exists and what type it is.


Please read this before commenting