PHP File Create and Write
In this PHP tutorial we will learn how to create a file and how to write to a file on the server.
- Create a File – touch() ,
- Create a File, if does not exist – fopen()
- Write to a File – fwrite()
PHP – Create a File
The touch() function is used to create a file on server. The fopen() function is also used to create a file in PHP. If we use fopen() function on a file the file does not exist, then it will create it. The touch() function and fopen() work same for creating a file on server where the php file directory code.
The PHP touch() function Syntax :
<?php
touch(“filename with extension”);
?>
PHP touch() function example
Here we use PHP touch() function to create a new file called ‘abc.txt’, ‘abc.doc’ and ‘abc.pdf’ on server.
<?php
//create text file
touch("abc.txt");
//create ms word .doc file
touch("abc.doc");
//create pdf file
touch('abc.pdf');
?>
When run above php code the file abc.txt, abc.pdf and abc.doc will be created in PHP program folder.
PHP fopen() function
When we use fopen() function for creating a new file, must assign mode character with function (w) for writing mode or (a) for appending mode.
fopen() syntax :
<?php
fopen(“filename with extension”, “mode char”);
?>
Example of fopen() function
<?php
//create text file
fopen("abc.txt","w");
//create ms word .doc file
fopen("abc.doc","w");
//create pdf file
fopen('abc.pdf',"w");
?>
The fopen() function has following modes :
- w = write only. if file exist open it, if not then create a new file.
- w+ = read/write
- r = read only
- r += read / write
- a = append file
- a+ = read / append
- x = write only. create new file, returns error if file already exists.
- x+ = read/write.
PHP fwrite() Function
The PHP fwrite() function is used to write to a file means write contents inside the file.
PHP fwrite() syntax
<?php
fwrite(“filename”,”text to be written”);
?>
The fwrite() function has first parameter is file name and the second parameter is text to be written in file.
fwrite() function example
For write context to file we must use fopen() function to open the file and then use fwrite() function for write to file.
<?php
//open file abc.txt
$myfile = fopen("abc.txt", "w");
$text = "Meera Academy";
fwrite($myfile, $text);
fclose($myfile);
?>
The output is : when we open abc.txt file it has content like : “Meera Academy”. Here, we first open the file abc.txt and write some text using fwrite() function and then finally close the file using fclose() function.
PHP form example of fwrite()
<html>
<head>
<title>PHP File create/write Example</title>
</head>
<body>
<FORM method="POST">
Enter String : <input type="text" name="name"> <br/>
<br/>
<input type="submit" name="Submit1" value="Write File">
</FORM>
<?php
if(isset($_POST['Submit1']))
{
//open file abc.txt in append mode
$myfile = fopen("abc.txt", "a");
$text = $_POST["name"];
fwrite($myfile, $text);
fclose($myfile);
}
?>
</body>
</html>
The output is :