PHP provides a set of file system functions that allow developers to easily interact with files and directories. Common file operations include opening, reading, writing, deleting, renaming, and more, while directory operations include creating, deleting, listing files, checking directories, and changing working directories. This article will help you understand how to use these functions and how to apply them in real projects through examples.
PHP offers several useful file operation functions. Some of the most common ones include:
<?php $file = 'my_file.txt'; $data = 'Hello, world!'; $handle = fopen($file, 'w'); fwrite($handle, $data); fclose($handle); echo 'File written'; ?>
Similarly, PHP offers several functions to interact with directories:
<?php $directory = 'new_directory'; mkdir($directory); echo 'Directory created'; ?>
Here’s an example of how to upload a file using PHP file system functions:
<?php if ($_FILES['my_file']['error'] === 0) { $target_dir = 'uploads/'; $target_file = $target_dir . basename($_FILES['my_file']['name']); // Check if file already exists if (file_exists($target_file)) { echo 'File already exists'; } else { // Move the uploaded file to the target directory if (move_uploaded_file($_FILES['my_file']['tmp_name'], $target_file)) { echo 'File uploaded successfully'; } else { echo 'File upload failed'; } } } ?>
This article covered how to use PHP file system functions for managing files and directories, along with real-world examples of file uploads. By mastering these basic operations, you can efficiently handle file and directory tasks in PHP. Stay tuned for more PHP development tips on our website.