CRUD files using php

How to create, read, update and delete files in PHP?

0 / 0 3 Mins Admin

January 11, 2023

10 Comments

You can perform basic Create, Read, Update, and Delete (CRUD) operations on files using a variety of built-in functions in PHP. For example, you can use a combination of the following functions to create, delete, read, and update files:

  • fopen(): Opens a file or URL.
  • fclose(): Closes an open file handle.
  • fwrite(): Writes data to an open file.
  • fread(): Reads data from files in PHP.
  • file_put_contents(): Writes data to a file.
  • file_get_contents(): Reads data from a file.
  • unlink(): Deletes a file.
  • file_exists(): Checks if a file exists.
  • is_writable(): Checks if a file is writable.

Here is an example of how you can use these functions to create, delete, read, and update a file in PHP:

// Create a file
$file = 'myfile.txt';
$handle = fopen($file, 'w');
fwrite($handle, 'Hello, world!');
fclose($handle);

// Read a file
$contents = file_get_contents($file);
echo $contents;

// Update a file
$handle = fopen($file, 'w');
fwrite($handle, 'Hello, world! How are you today?');
fclose($handle);

// Delete a file
unlink($file);

// Check if a file exists
if (file_exists($file)) {
    echo "The file exists.";
} else {
    echo "The file does not exist.";
}

// Check if a file is writable
if (is_writable($file)) {
    echo "The file is writable.";
} else {
    echo "The file is not writable.";
}

Conclusion

To create new files in PHP, you can use the fopen() function, which opens a file or creates a new one if it doesn’t already exist. You can then use the fwrite() function to write data to the file.

To read the contents of a file, you can use the fread() function, which reads a specified number of bytes from a file. Alternatively, you can use the file_get_contents() function to read the entire contents of a file into a string.

To update the contents of a file, you can use the file_put_contents() function, which writes data to a file, overwriting its previous contents. Alternatively, you can use the fopen() and fwrite() functions together to open an existing file and write new data to it.

To delete a file, you can use the unlink() function, which deletes a specified file. It is necessary to specify a path of the file as an argument in this function.

It’s important to note that all of these file functions require proper permissions to the file or folder you are handling, otherwise these operations will fail. Also, you can use fclose() function after finishing the reading/writing operation.

Additionally, you can use file-handling classes like SplFileObject, SplFileInfo and DirectoryIterator which will provide more functionality and better handling of files.