codescracker


php

PHP Open File



« Previous Tutorial Next Tutorial »


To open a file in PHP, use fopen() function. Let's see how to open any file on the web using PHP.

PHP Open File Syntax

Below is the general form to open any file in PHP.

fopen(filename, "filemode");

Let's see the list of file modes used in opening a file along with its description.

PHP File Opening Modes

The table given below lists file modes available in PHP, used to open a file.

File Mode Code File Mode Description
w Opens a file for writing purpose. Creates a new file on opening non-existing file
w+ Opens a file for both reading and writing purpose. Creates a new file on opening non-existing file
r Opens a file for reading purpose
r+ Opens a file for both reading and writing purpose
a Opens a file for appending purpose. Creates a new file on opening non-existing file
a+ Opens a file for both reading and appending purpose. Creates a new file on opening non-existing file

Appending is used only if you don't want to remove the previous content of the file.

PHP Open File Example

Let's see how to open file in PHP. This example opens a file in reading mode.

<html>
<head>
	<title>Open a File in PHP</title>
</head>
<body>
<?php
	$file = fopen("new_file.txt", "r");
	if($file)
	{
		echo "<p>File <b>new_file.txt</b> opened successfully.</p>";
	}
	else 
	{
		echo "<p>Error occurred in opening the file <b>new_file.txt</b></p>";
	}
	fclose($file);
?>
</body>
</html>

Here is the sample output produced by the above PHP file opening example code:

php open file

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test