PHP provides a variety of built-in functions for working with files and directories.
To open a file in PHP, you can use the fopen() function, which takes the file path and mode as arguments. The mode can be “r” for reading, “w” for writing, “a” for appending, and various other options. Once a file is open, you can read from it or write to it using the fread(), fwrite(), and fclose() functions.
For example, the following code reads the contents of a file into a string:
$file = fopen("example.txt", "r"); $contents = fread($file, filesize("example.txt")); fclose($file);
Similarly, you can create and write to a new file using the following code:
$file = fopen("example.txt", "w"); fwrite($file, "Hello, World!"); fclose($file);
To work with directories, PHP provides several functions such as scandir() and opendir() which allows you to read the contents of a directory, and mkdir() and rmdir() for creating and deleting directories.
Additionally, you can check if a file or directory exists with the file_exists() function, get information about a file with the stat() function, and more.
It’s important to note that when working with files and directories, it’s important to use appropriate error handling and to validate user input when working with user-supplied data to avoid security vulnerabilities such as file inclusion attacks.