Home » PHP » PHP File Example

About Olayemi Odunayo

Olayemi Odunayo
I am a programmer and web developer, who has experience in developing websites and writing desktop and mobile applications. I have worked with both schematic and schemaless databases. I am also familiar with third party API and working with cloud servers. I do programming on the client side with Java, JavaScript, html, Ajax and CSS while I use PHP for server side programming.

PHP File Example

In this example we will learn about files and directories, we will also learn how to manipulate them with PHP. PHP allows you to work with files and directories stored on the web server.

Files are persistent storage, they are stored on the hard drive and retain there data even after the computer is shut down. Directories are used to store files (and even other directories) hierarchically. Files can store different kinds of data.
 
 

 
For this example we will use:

  1. A computer with PHP>= 5.5 installed
  2. notepad++

1. Checking If Files Exists

PHP provides some functions that enable you to access useful file information. We can use function file_exists() to discover whether a file exists. To get the size of a file we can use filesize()

index.php

  
<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title>PHP File Example</title>
	
	</head>
	<body onload=init()>
<?php
if(file_exists("file.html")){
echo filesize("file.html");

}
else{

echo "File Does Not Exist";
}

?>
	</body>
	</html>

In the above script we check if a particular file exists(line 24), if it exists we echo the file size (line 25)

1.1 Retrieving File Name From Path

PHP functionbasename() retrieves a file name from it’s directory path. The basename() will return a file name from a given path, it basically retrieves the last whole string after the rightmost slash.

 
$name=basename("/home/server/example/file.txt");

You can specify a directory name path instead, in which case the rightmost directory name is returned. Here’s an example that assigns the value example to $name

 
$name=basename("/home/server/example");

If we don’t want the filename extension or suffix, you can strip that off too by supplying the suffix as a second argument to basename()

 
$name = basename("/home/server/example/file.txt",".txt");

1.2 Time Related Properties

These properties depend on the operating system in which the files were created and modified. On unix platforms such as Linux, properties include the time that the file was last modified, the time it was accessed and the user permission set on the file.

  • fileatime() Returns the time at which the file was last accessed as a unix timestamp.
  • filectime() Returns the time at which the file was last as a unix timestamp.
  • filemtime() Returns the time at which the file was last modified as a unix timestamp.

1.3 Reading Files

To read a file from PHP, we need to open it (Some PHP functions allow you to read a file without opening it). After we are through with the file we close it.
We open a file withfopen() and close it with fclose()
fopen takes two parameters the first parameter is the file we want to open and the second parameter is the mode in which we use to open the file.
The second argument can be one of the following

  • r : Opens the file for reading. The file pointer is placed at the beginning.
  • r+ : Opens the file for reading and writing.
  • w : Opens the file for writing only.
  • w+ : Opens the file for reading and writing, any existing content will be deleted.
  • a : Opens the file for appending only. Data is written to the end of an existing file.
  • a+ : Opens the file for reading and appending. Data is written to the end of an existing file. If the file does not exist, PHP attempts to create it.

file.html

   
<h2>2 Getting Started</h2>
To demystify cookies in php, we would develop a simple web app that allows users select the font style and font size to display on a website and stores this preference.
<h3>2.1 Working With Cookies</h3>
Cookies identify a user. Cookies allow web developers store a small amount of data on the user browser(not more than 4kb). Each time a request is sent to the server, the cookies stored on the browser are automatically sent with the request and can be accessed by the server.
Cookies are reliable but they are not all that secure because attackers can easily tamper with them, so you should never use cookies alone to authenticate your users or store sensitive data in cookies (e.g passwords). Users can also turn off cookies support in there browsers, so you should be careful when the core functionality of your web app depends on cookies(if your web app depends on cookies to work properly, you should always check if cookies are supported in the browser and if it is not, alert the user about the error)
<h3>2.2 Creating cookies in php</h3>
To create a cookie in php we use the <code>setcookie(name,value,expires,path,domain,secure,httponly)</code> method which takes 7 parameters

The above document is the file we are about to read. We read and output the file content to the browser.

index2.php

 
<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title>Read File</title>
	
	</head>
	<body>
<?php
$myfile = fopen( "file.html" , "r" )
or die ( "Unable to open file!" );
echo fread($myfile,filesize( "file.html" ));
fclose($myfile);
?>



	</body>
	</html>

We open the file for reading (line 24). We read its content and close the file(line 26 and 27). The fread() function reads from an open file. Its first parameter contains the name of the file to read from, and the second parameter defines the number of bytes to read.
It’s considered good programming practice to close all files after you have finished using them. You don’t want the opened file taking up server resources. To close the file we use PHP fclose() function. It takes the name of the file (or a variable that holds the filename) we want to close as a parameter.

1.4 Using PHP readfile

PHP readfile() function is used to read a file without having to open the file.

index3.php

 
<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:hidden;
	padding:0%;
	border:0%;
	}
	 
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title>PHP File Example</title>
	
	</head>
	<body>
<?php
if(file_exists("file.html")){
echo readfile("file.html");

}
else{

echo "File Does Not Exist";
}

?>
	</body>
	</html>

1.5 Creating Files

The fopen() function is also used to create a file. If we call fopen() on a file that does not exist, it will create a new file, given that the file is opened for writing (w) or appending (a).

index4.php

<?php
$myfile = fopen( "test.html" , "w" )
or die ( "Unable to open file!" );
$txt= "e-mail(electronic mail) has become an integral part of the internet. Approximately all tech savy people have an email address, if you have a facebook account, you sure registered it with an email address.
e-mails are simply messages that can contain text, attachments and are sent through a computer network to individuals or groups of individuals.
In this example we are going to learn how to send e-mails with PHP.
For this example we will use:";
fwrite($myfile, $txt);
fclose($myfile);
?>

In this example we call fopen (line 2)on a file that does not exist. This creates a new file. We also write to the file by using PHP fwrite()(line 8) function, which takes two parameters, the file we would write to and the text to write.

2. Summary

In this example we learnt about files and directories. We also learnt how to open, close, create and write to files with PHP functions.

3. Download the source code

Download
You can download the full source code of this example here: phpfileexample
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments