Php Basic File Handling Create a File
Learn PHP basic file handling create a file
Published
- PHP File Handling
- How to create a single file using PHP fopen() function
- How to create a Multiple files using PHP fopen() function
- fopen() common file modes
PHP File Handling
PHP provides out of the box functionality to create files. Using PHP fopen function you can create files or read file.
If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
Syntax
<?php
fopen( string $file_name", string $mode [, bool $use_include_path = FALSE]) ;
How to create a single file using PHP fopen() function
<?php
$file_name = 'customer-list1.csv';
$fh = fopen($file_name, 'w') or die("Can't create file");
echo $file_name. " File created.";
How to create a Multiple files using PHP fopen() function
If you need to create a number of files the good way to keep all files name into array and loop the fopen function to create any number of files.
<?php
$new_files = array (
'List1' => 'customer-list1.csv',
'List2' => 'customer-list2.csv',
'List3' => 'customer-list3.csv'
);
if (!empty($new_files)){
foreach ( $new_files as $key => $file_name ) {
$fh = fopen($file_name, 'w') or die("Can't create file");
echo $file_name. " File created.<br />";
}
}
fopen() common file modes
- ‘r’ Open for reading only; place the file pointer at the beginning of the file.
- ‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
- ‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
- ‘w+’ Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
- ‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
- ‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.