codescracker


php

PHP Create File



« Previous Tutorial Next Tutorial »


Here you will learn about how to create a file using PHP with example.

To create a file in PHP, use w as file opening mode. This mode is used to write some content to an existing file, and in case if file doesn't exist inside the current directory, then this mode creates a new file.

PHP Create File Example

Here is step by step example shows how to create a file using PHP.

Before creating any new file inside the current directory, first see the screenshot of the folder of current directory, that is, C:\xampp\htdocs\

php create file

Here is an example used to create a new file in PHP.

<html>
<head>
	<title>Create a File in PHP</title>
</head>
<body>
<?php
	// new_file.txt is the file, that is going
	// to create using this PHP example
	// let's initialize that filename with extension 
	// to a php variable named $create_file_name
	$create_file_name = 'new_file.txt';
	// below code will creates the file inside 
	// the current directory
	$file_handle = fopen($create_file_name, 'w');
	// below code checks if file successfully creates or not
	if(!empty($file_handle))
	{
		echo "<p>File named <b>new_file.txt</b> is created successfully.</p>";
	}
	// else block is used, if error occurred in creating the file
	else 
	{
		echo "<p>Error occurred in creating the file.</p>";
	}
	// close the file
	fclose($file_handle);
?>
</body>
</html>

Below is the sample output produced by the above example code in PHP to create a new file.

php create file example

After running the above file creating program in PHP, you will see there is a file named new_file.txt is created inside the current directory. Here is the screenshot of the current directory after running the above file creating program:

creating new file in php

If the file new_file.txt already exists inside the current directory, then on running the above code in your browser, no action will be performed and the file will still be exist after running and re-running the above program as w mode only creates a new file, if file doesn't exist.


« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test