PHP File Handling
PHP provides various ways to manipulate files and folders on the server. In this article, we will discuss the file handling capabilities of PHP, specifically how to create, read, update, and delete files using PHP.
Creating a File
To create a file using PHP, you need to use the fopen() function. This function takes two parameters: the name of the file you want to create and the mode in which you want to open the file.
PHP open a file for writing
$file = fopen("test.txt", "w");In this example, we are creating a file named "test.txt" and opening it in write mode ("w"). Once the file is open, you can write to it using the fwrite() function.
PHP write to a file by using fwrite
fwrite($file, "Hello World");After writing to the file, it's important to close it using the fclose() function.
PHP close file after writing
fclose($file);Reading a File
To read the contents of a file, you need to use the file_get_contents() function. This function takes a single parameter: the name of the file you want to read.
PHP get file content by using file_get_contents
$content = file_get_contents("test.txt");
echo $content;This will output the contents of the file, which in this case is "Hello World".
Updating a File
To update the contents of a file, you can use the file_put_contents() function. This function takes two parameters: the name of the file you want to update and the new contents of the file.
PHP put content to a file by using file_put_contents
$content = "Hello World Again";
file_put_contents("test.txt", $content);Deleting a File
To delete a file, you can use the unlink() function. This function takes a single parameter: the name of the file you want to delete.
PHP delete a file by using unlink function
unlink("test.txt");Summary
File handling is a crucial aspect of server-side programming. PHP provides various functions to make it easy to manipulate files and folders on the server. In this article, we discussed how to create, read, update, and delete files using PHP.
Practice
What are the correct ways to open a file in PHP?