PHP - SPLessons

PHP File Permissions

Chapter 26

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP File Permissions

PHP File Permissions

PHP Open File – fopen()

shape Description

fopen() function is used to give PHP File Permissions like opening a file and gives more option to control the file.

Mode Description
r Represents open a file for read.File pointer points to the initial point of the file.
w Represents open empty file for writing.File pointer points to the initial point of the file.
a Represents open a file to append the data to the existing file without erasing the existing data. File pointer begins at the end of the file. If no file exist, a new file is created.
x Represent creation of a new file for write purpose only. Returns FALSE and an error if file already exists.
r+ Represents open a binary file for read and write.File pointer points to the initial point of the file.
w+ Represents open a binary file for write and read
r+ Represents open a binary file for append and read
x+ represents creation of a new file to read/write. Returns FALSE and an error if file already exists.

shape Example


<!DOCTYPE html>
<html>
	<body>
		<?php 
			$filename = fopen("welcome.txt", "r") or die("Unable to open file!"); 
			echo readfile($filename); 
			fclose($filename); 
		?>
	</body>
</html>

PHP Read File – fread()

shape Description

fread() function can be used to read the file, which is opened with fopen.

Syntax:

fread($filename,filesize(“file.txt”));

where the first parameter in fread() function is file name and the second parameter is filesize, representing how many bytes of data have to read.

shape Examples

<!DOCTYPE html>
<html>
	<body>	 
		<?php 
			$filename = fopen("random.txt", "r") or die("Unable to open file!"); 
			echo fread($filename,filesize("random.txt")); 
			fclose($filename); 
		?>
	</body>
</html>

PHP Close File – fclose()

shape Description

The fclose() will close the file, which is opened with fopen() function. Always do not forgot to close the file once the task is completed.It is a good programming practice to close the file after completing the task, so that server resources will not be wasted.

shape Examples

<!DOCTYPE html> 
<html>
	<body>
		<?php 
			$filename = fopen("random.txt", "r") or die("Unable to open file!"); 
			echo fread($filename,filesize("random.txt")); 
			fclose($filename); 
		?> 
	</body>
</html>

Summary

shape Points

  • fopen() function is used to open a file.
  • fread() function can be used to read the file,
  • fclose() will close the file.