Create File in PHP and Write to It: Code Examples
Learn how to create a file in PHP and write content to it using file_put_contents and fopen. Clear examples help you save data safely and read it back.


PHP offers a range of functions for creating files and writing to them. Among these functions, the most commonly used ones are “fopen()”, “fwrite()” and “fclose()”.
The following code block creates a file named “example.txt” inside a specific directory and writes the string “Hello, this is the text inside an example file.” into it:
<?php
// Directory path
$directory = "example_directory/";
// File name
$fileName = "example.txt";
// File path
$filePath = $directory . $fileName;
// File open mode
$fileMode = "w";
// Open the file
$file = fopen($filePath, $fileMode);
// Write into the file
fwrite($file, "Merhaba, bu bir örnek dosya içerisindeki yazıdır.");
// Close the file
fclose($file);
?>
In the code block, first the directory path “example_directory/” and the file name “example.txt” are defined. Then the file path is built and “w” (write) is used as the file open mode. This mode deletes the file’s contents if the file exists and creates a new file. The file is opened with the “fopen()” function and the text is written into the file with the “fwrite()” function. Finally, the file is closed with the “fclose()” function.
Other important topics and related topics used in this example are as follows:
- Building a file path
- File open modes (such as r, w, a, x)
- The fopen() function
- The fwrite() function
- The fclose() function
Creating files and writing to them are among the operations frequently used when developing web applications with PHP. That’s why it’s important to know these operations well and put them into practice. In addition, there are some points to watch out for in file operations:
- Defining the file path correctly: Defining the file path correctly is very important in file operations. If the file path is defined incorrectly, opening, writing to and reading the file cannot be performed.
- Using file open modes correctly: File open modes matter in file operations. For example, the “r” mode reads a file, the “w” mode writes to a file and the “a” mode appends to a file.
- Authorization in file operations: In file operations, the user’s authorization must be checked. For example, the user needs to have permission to create, write to or read the file.
In conclusion, creating files and writing to them with PHP is done using the “fopen()”, “fwrite()” and “fclose()” functions. These operations are among those frequently used when developing web applications, so it’s important to know them well and apply them. In addition, points such as defining the file path correctly, using file open modes correctly and checking authorization are also things to watch out for in file operations.
Share it if it helped


