SlideShare a Scribd company logo
Diploma in Web Engineering
Module VIII: File handling with PHP
Rasan Samarasinghe
ESOFT Computer Studies (pvt) Ltd.
No 68/1, Main Street, Pallegama, Embilipitiya.
Contents
1. include and require Statements
2. include and require
3. include_once Statement
4. Validating Files
5. file_exists() function
6. is_dir() function
7. is_readable() function
8. is_writable() function
9. is_executable() function
10. filesize() function
11. filemtime() function
12. filectime() function
13. fileatime() function
14. Creating and deleting files
15. touch() function
16. unlink() function
17. File reading, writing and appending
18. Open File - fopen()
19. Close File - fclose()
20. Read File - fread()
21. Read Single Line - fgets()
22. Check End-Of-File - feof()
23. Read Single Character - fgetc()
24. Seek File - fseek()
25. Write File - fwrite()
26. Write File - fputs()
27. Lock File - flock()
28. Working with Directories
29. Create directory - mkdir()
30. Remove directory - rmdir()
31. Open directory - opendir()
32. Read directory - readdir()
include and require Statements
The include and require statements takes all the
text/code/markup that exists in the specified file and
copies it into the file that uses the include statement.
Syntax:
include 'filename';
or
require 'filename';
include statement example 1 (menu.php file)
<?php
echo '<a href="/index.php">Home</a> |
<a href="courses.php">Courses</a> |
<a href="branches.php">Branches</a> |
<a href="about.php">About Us</a> |
<a href="contact.php">Contact Us</a>';
?>
include statement example 1 (index.php file)
<html>
<body>
<div>
<?php include 'menu.php';?>
</div>
<h1>Welcome to Esoft Metro Campus!</h1>
<p>The leader in professional ICT education.</p>
</body>
</html>
include statement example 2 (core.php file)
<?php
function showFooter(){
echo "<p>Copyright &copy; " . date("Y") . "
Wegaspace.com</p>";
}
?>
include statement example 2 (index.php file)
<html>
<body>
<h1>Welcome to Wegaspace!</h1>
<p>The most unique wap community ever!</p>
<?php
include 'footer.php';
showFooter();
?>
</body>
</html>
include and require
The include and require statements are identical,
except upon failure:
• require will produce a fatal error
(E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING)
and the script will continue
include_once Statement
The require_once() statement will check if the file
has already been included, and if so, not include
(require) it again.
Syntax:
include_once 'filename';
include_once statement example
world.php file
<?php
echo "Hello World!<br/>";
?>
srilanka.php file
<?php
echo "Hello Sri Lanka!<br/>";
?>
include_once statement example
<html>
<body>
<p>
<?php
include 'world.php';
include 'world.php'; // includes the file again
include_once 'srilanka.php';
include_once 'srilanka.php'; // not includes the file again
?>
</p>
</body>
</html>
Validating Files
• file_exists() function
• is_dir() function
• is_readable() function
• is_writable() function
• is_executable() function
• filesize() function
• filemtime() function
• filectime() function
• fileatime() function
file_exists() function
The file_exists() function checks whether or not a
file or directory exists.
This function returns TRUE if the file or directory
exists, otherwise it returns FALSE.
Syntax:
file_exists(path)
file_exists() function
<?php
var_dump(file_exists("test.txt"));
?>
is_dir() function
The is_dir() function checks whether the specified
file is a directory.
This function returns TRUE if the directory exists.
Syntax:
is_dir(file)
is_dir() function
$file = "images";
if(is_dir($file)){
echo ("$file is a directory");
} else {
echo ("$file is not a directory");
}
is_readable() function
The is_readable() function checks whether the
specified file is readable.
This function returns TRUE if the file is readable.
Syntax:
is_readable(file)
is_readable() function
$file = "test.txt";
if(is_readable($file)){
echo ("$file is readable");
} else {
echo ("$file is not readable");
}
is_writable() function
The is_writable() function checks whether the
specified file is writeable.
This function returns TRUE if the file is writeable.
Syntax:
is_writable(file)
is_writable() function
$file = "test.txt";
if(is_writable($file)) {
echo ("$file is writeable");
} else {
echo ("$file is not writeable");
}
is_executable() function
The is_executable() function checks whether the
specified file is executable.
This function returns TRUE if the file is executable.
Syntax:
is_executable(file)
is_executable() function
$file = "setup.exe";
if(is_executable($file)) {
echo ("$file is executable");
} else {
echo ("$file is not executable");
}
filesize() function
The filesize() function returns the size of the
specified file.
This function returns the file size in bytes on
success or FALSE on failure.
Syntax:
filesize(filename)
filesize() function
echo filesize("test.txt");
filemtime() function
The filemtime() function returns the last time the
file content was modified.
This function returns the last change time as a Unix
timestamp on success, FALSE on failure.
Syntax:
filemtime(filename)
filemtime() function
echo filemtime("test.txt");
echo "<br />";
echo "Last modified: ".date("F d Y
H:i:s.",filemtime("test.txt"));
filectime() function
The filectime() function returns the last time the
specified file was changed.
This function returns the last change time as a Unix
timestamp on success, FALSE on failure.
Syntax:
filectime(filename)
filectime() function
echo filectime("test.txt");
echo "<br />";
echo "Last change: ".date("F d Y
H:i:s.",filectime("test.txt"));
fileatime() function
The fileatime() function returns the last access time
of the specified file.
This function returns the last access time as a Unix
timestamp on success, FALSE on failure.
Syntax:
fileatime(filename)
fileatime() function
echo fileatime("test.txt");
echo "<br />";
echo "Last access: ".date("F d Y
H:i:s.",fileatime("test.txt"));
Creating and deleting files
• touch() function
• unlink() function
touch() function
The touch() function sets the access and
modification time of the specified file.
This function returns TRUE on success, or FALSE on
failure.
Syntax:
touch(filename, time, atime)
touch() function
touch("test.txt");
touch("test.txt", mktime(8,40,20,2,10,1988));
unlink() function
The unlink() function deletes a file.
This function returns TRUE on success, or FALSE on
failure.
Syntax:
unlink(filename, context)
unlink() function
$file = "test.txt";
if (!unlink($file)) {
echo ("Error deleting $file");
} else {
echo ("Deleted $file");
}
File reading, writing and appending
• Open File - fopen()
• Close File - fclose()
• Read File - fread()
• Read Single Line - fgets()
• Check End-Of-File - feof()
• Read Single Character - fgetc()
• Seek File - fseek()
• Write File - fwrite()
• Write File - fputs()
• Lock File - flock()
Open File - fopen()
The fopen() function opens a file or URL.
If fopen() fails, it returns FALSE and an error on
failure.
Syntax:
fopen(filename, mode, include_path, context)
File open modes
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w
Open a file for write only. Erases the contents of the file or creates a new
file if it doesn't exist. File pointer starts at the beginning of the file
a
Open a file for write only. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x
Creates a new file for write only. Returns FALSE and an error if file already
exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+
Open a file for read/write. Erases the contents of the file or creates a new
file if it doesn't exist. File pointer starts at the beginning of the file
a+
Open a file for read/write. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x+
Creates a new file for read/write. Returns FALSE and an error if file already
exists
Open File - fopen()
$file = fopen("test.txt","r");
$file = fopen("/home/test/test.txt","r");
$file = fopen("/home/test/test.gif","wb");
$file = fopen("http://www.example.com/","r");
$file =
fopen("ftp://user:password@example.com/test.txt
","w");
Close File - fclose()
The fclose() function closes an open file.
This function returns TRUE on success or FALSE on
failure.
Syntax:
fclose(file)
Close File - fclose()
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
Read File - fread()
The fread() reads from an open file.
The function will stop at the end of the file or when it
reaches the specified length, whichever comes first.
This function returns the read string, or FALSE on
failure.
Syntax:
fread(file, length)
Read File - fread()
$file = fopen("test.txt","r");
fread($file, filesize("test.txt"));
fclose($file);
Read Single Line - fgets()
The fgets() function returns a line from an open file.
The fgets() function stops returning on a new line,
at the specified length, or at EOF, whichever comes
first.
This function returns FALSE on failure.
Syntax:
fgets(file, length)
Read Single Line - fgets()
$file = fopen("test.txt","r");
echo fgets($file). "<br />";
fclose($file);
Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF)
has been reached.
This function returns TRUE if an error occurs, or if
EOF has been reached. Otherwise it returns FALSE.
Syntax:
feof(file)
Check End-Of-File - feof()
$file = fopen("test.txt", "r");
//Output a line of the file until the end is reached
while(! feof($file)) {
echo fgets($file). "<br />";
}
fclose($file);
Read Single Character - fgetc()
The fgetc() function returns a single character from
an open file.
Syntax:
fgetc(file)
Read Single Character - fgetc()
$file = fopen("test2.txt", "r");
while (! feof ($file)) {
echo fgetc($file);
}
fclose($file);
Seek File - fseek()
The fseek() function seeks in an open file.
This function moves the file pointer from its current
position to a new position, forward or backward,
specified by the number of bytes.
This function returns 0 on success, or -1 on failure.
Seeking past EOF will not generate an error.
Syntax:
fseek(file, offset, whence)
Seek File - fseek()
$file = fopen("test.txt", "r");
// read first line
fgets($file);
// move back to beginning of file
fseek($file, 0);
Write File - fwrite()
The fwrite() writes to an open file.
The function will stop at the end of the file or when it
reaches the specified length, whichever comes first.
This function returns the number of bytes written, or
FALSE on failure.
Syntax:
fwrite(file, string, length)
Write File - fwrite()
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
Write File - fputs()
The fputs() writes to an open file.
The function will stop at the end of the file or when it
reaches the specified length, whichever comes first.
This function returns the number of bytes written on
success, or FALSE on failure.
Syntax:
fputs(file, string, length)
Write File - fputs()
$file = fopen("test.txt","w");
echo fputs($file,"Hello World. Testing!");
fclose($file);
Lock File - flock()
The flock() function locks or releases a file.
This function returns TRUE on success or FALSE on
failure.
Syntax:
flock(file, lock, block)
Lock File - flock()
$file = fopen("test.txt", "w+");
if (flock($file, LOCK_EX)) {
fwrite($file, "Write something");
flock($file, LOCK_UN);
} else {
echo "Error locking file!";
}
fclose($file);
Working with Directories
• Create directory - mkdir()
• Remove directory - rmdir()
• Open directory - opendir()
• Read directory - readdir()
Create directory - mkdir()
The mkdir() function creates a directory.
This function returns TRUE on success, or FALSE on
failure.
Syntax:
mkdir(path, mode, recursive, context)
Create directory - mkdir()
mkdir("testing", 0775);
Remove directory - rmdir()
The rmdir() function removes an empty directory.
This function returns TRUE on success, or FALSE on
failure.
Syntax:
rmdir(dir, context)
Remove directory - rmdir()
$path = "images";
if(!rmdir($path)) {
echo ("Could not remove $path");
}
Open directory - opendir()
The opendir() function opens a directory handle.
Syntax:
opendir(path, context);
Open directory - opendir()
$dir = "images";
if ($dh = opendir($dir)){
echo "$dir directory opened";
}
closedir($dh);
Read directory - readdir()
The readdir() function returns the name of the next
entry in a directory.
Syntax:
readdir(dir_handle);
Read directory - readdir()
$dir = "images";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
The End
http://twitter.com/rasansmn

More Related Content

What's hot

File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
Anil Dutt
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
Gaurav Garg
 
File in c
File in cFile in c
File in c
Prabhu Govind
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
thirumalaikumar3
 
File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
File handling in C
File handling in CFile handling in C
File handling in C
Kamal Acharya
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
Vibrant Technologies & Computers
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappersPositive Hack Days
 
Logrotate sh
Logrotate shLogrotate sh
Logrotate sh
Ben Pope
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examplesMuhammed Thanveer M
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
Sonya Akter Rupa
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
Mahendra Yadav
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 

What's hot (20)

File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
File in c
File in cFile in c
File in c
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
File in C language
File in C languageFile in C language
File in C language
 
Unit5
Unit5Unit5
Unit5
 
File handling in C
File handling in CFile handling in C
File handling in C
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File operations in c
File operations in cFile operations in c
File operations in c
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
File Management in C
File Management in CFile Management in C
File Management in C
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
Logrotate sh
Logrotate shLogrotate sh
Logrotate sh
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 

Viewers also liked

DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
Rasan Samarasinghe
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
Rasan Samarasinghe
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web Designing
Rasan Samarasinghe
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
Rasan Samarasinghe
 
Ahmad sameer types of computer
Ahmad sameer types of computerAhmad sameer types of computer
Ahmad sameer types of computer
Sameer Nawab
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
Arjun Sridhar U R
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
yugandhar vadlamudi
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
Arjun Sridhar U R
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
Pokequesthero
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
Arjun Sridhar U R
 
02basics
02basics02basics
02basics
Waheed Warraich
 
Core java online training
Core java online trainingCore java online training
Core java online training
Glory IT Technologies Pvt. Ltd.
 
09events
09events09events
09events
Waheed Warraich
 
Savr
SavrSavr
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
Arjun Sridhar U R
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
Mumbai Academisc
 

Viewers also liked (20)

DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web Designing
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Ahmad sameer types of computer
Ahmad sameer types of computerAhmad sameer types of computer
Ahmad sameer types of computer
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
02basics
02basics02basics
02basics
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
09events
09events09events
09events
 
Savr
SavrSavr
Savr
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 

Similar to DIWE - File handling with PHP

PHP File Handling
PHP File Handling PHP File Handling
PHP File Handling
Degu8
 
Files in PHP.pptx g
Files in PHP.pptx                      gFiles in PHP.pptx                      g
Files in PHP.pptx g
FiromsaDine
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
Md. Imran Hossain Showrov
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
VrushaliSolanke
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
yndaravind
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
RavindraSalunke3
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
AssadLeo1
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
sudhakargeruganti
 
File handling C program
File handling C programFile handling C program
File handling C program
Thesis Scientist Private Limited
 
lecture 10.pptx
lecture 10.pptxlecture 10.pptx
lecture 10.pptx
ITNet
 
File system
File systemFile system
File system
Gayane Aslanyan
 
PHP Filing
PHP Filing PHP Filing
PHP Filing
Nisa Soomro
 
File management
File managementFile management
File management
sumathiv9
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
Jamshid Hashimi
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
Chap 5 php files part 1
Chap 5 php files part 1Chap 5 php files part 1
Chap 5 php files part 1
monikadeshmane
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
sangeeta borde
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 

Similar to DIWE - File handling with PHP (20)

PHP File Handling
PHP File Handling PHP File Handling
PHP File Handling
 
Files in PHP.pptx g
Files in PHP.pptx                      gFiles in PHP.pptx                      g
Files in PHP.pptx g
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
File management
File managementFile management
File management
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
File handling C program
File handling C programFile handling C program
File handling C program
 
lecture 10.pptx
lecture 10.pptxlecture 10.pptx
lecture 10.pptx
 
File system
File systemFile system
File system
 
PHP Filing
PHP Filing PHP Filing
PHP Filing
 
File management
File managementFile management
File management
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
Files nts
Files ntsFiles nts
Files nts
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
Chap 5 php files part 1
Chap 5 php files part 1Chap 5 php files part 1
Chap 5 php files part 1
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 

More from Rasan Samarasinghe

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptx
Rasan Samarasinghe
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrum
Rasan Samarasinghe
 
Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agile
Rasan Samarasinghe
 
IT Introduction (en)
IT Introduction (en)IT Introduction (en)
IT Introduction (en)
Rasan Samarasinghe
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling Language
Rasan Samarasinghe
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
Rasan Samarasinghe
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Rasan Samarasinghe
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with Git
Rasan Samarasinghe
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
Rasan Samarasinghe
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
Rasan Samarasinghe
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality Management
Rasan Samarasinghe
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project Management
Rasan Samarasinghe
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
Rasan Samarasinghe
 
DISE - Database Concepts
DISE - Database ConceptsDISE - Database Concepts
DISE - Database Concepts
Rasan Samarasinghe
 
DISE - OOAD Using UML
DISE - OOAD Using UMLDISE - OOAD Using UML
DISE - OOAD Using UML
Rasan Samarasinghe
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
Rasan Samarasinghe
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software Engineering
Rasan Samarasinghe
 

More from Rasan Samarasinghe (20)

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptx
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrum
 
Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agile
 
IT Introduction (en)
IT Introduction (en)IT Introduction (en)
IT Introduction (en)
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling Language
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with Git
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality Management
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project Management
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
 
DISE - Database Concepts
DISE - Database ConceptsDISE - Database Concepts
DISE - Database Concepts
 
DISE - OOAD Using UML
DISE - OOAD Using UMLDISE - OOAD Using UML
DISE - OOAD Using UML
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software Engineering
 

Recently uploaded

Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 

Recently uploaded (20)

Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 

DIWE - File handling with PHP

  • 1. Diploma in Web Engineering Module VIII: File handling with PHP Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
  • 2. Contents 1. include and require Statements 2. include and require 3. include_once Statement 4. Validating Files 5. file_exists() function 6. is_dir() function 7. is_readable() function 8. is_writable() function 9. is_executable() function 10. filesize() function 11. filemtime() function 12. filectime() function 13. fileatime() function 14. Creating and deleting files 15. touch() function 16. unlink() function 17. File reading, writing and appending 18. Open File - fopen() 19. Close File - fclose() 20. Read File - fread() 21. Read Single Line - fgets() 22. Check End-Of-File - feof() 23. Read Single Character - fgetc() 24. Seek File - fseek() 25. Write File - fwrite() 26. Write File - fputs() 27. Lock File - flock() 28. Working with Directories 29. Create directory - mkdir() 30. Remove directory - rmdir() 31. Open directory - opendir() 32. Read directory - readdir()
  • 3. include and require Statements The include and require statements takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Syntax: include 'filename'; or require 'filename';
  • 4. include statement example 1 (menu.php file) <?php echo '<a href="/index.php">Home</a> | <a href="courses.php">Courses</a> | <a href="branches.php">Branches</a> | <a href="about.php">About Us</a> | <a href="contact.php">Contact Us</a>'; ?>
  • 5. include statement example 1 (index.php file) <html> <body> <div> <?php include 'menu.php';?> </div> <h1>Welcome to Esoft Metro Campus!</h1> <p>The leader in professional ICT education.</p> </body> </html>
  • 6. include statement example 2 (core.php file) <?php function showFooter(){ echo "<p>Copyright &copy; " . date("Y") . " Wegaspace.com</p>"; } ?>
  • 7. include statement example 2 (index.php file) <html> <body> <h1>Welcome to Wegaspace!</h1> <p>The most unique wap community ever!</p> <?php include 'footer.php'; showFooter(); ?> </body> </html>
  • 8. include and require The include and require statements are identical, except upon failure: • require will produce a fatal error (E_COMPILE_ERROR) and stop the script • include will only produce a warning (E_WARNING) and the script will continue
  • 9. include_once Statement The require_once() statement will check if the file has already been included, and if so, not include (require) it again. Syntax: include_once 'filename';
  • 10. include_once statement example world.php file <?php echo "Hello World!<br/>"; ?> srilanka.php file <?php echo "Hello Sri Lanka!<br/>"; ?>
  • 11. include_once statement example <html> <body> <p> <?php include 'world.php'; include 'world.php'; // includes the file again include_once 'srilanka.php'; include_once 'srilanka.php'; // not includes the file again ?> </p> </body> </html>
  • 12. Validating Files • file_exists() function • is_dir() function • is_readable() function • is_writable() function • is_executable() function • filesize() function • filemtime() function • filectime() function • fileatime() function
  • 13. file_exists() function The file_exists() function checks whether or not a file or directory exists. This function returns TRUE if the file or directory exists, otherwise it returns FALSE. Syntax: file_exists(path)
  • 15. is_dir() function The is_dir() function checks whether the specified file is a directory. This function returns TRUE if the directory exists. Syntax: is_dir(file)
  • 16. is_dir() function $file = "images"; if(is_dir($file)){ echo ("$file is a directory"); } else { echo ("$file is not a directory"); }
  • 17. is_readable() function The is_readable() function checks whether the specified file is readable. This function returns TRUE if the file is readable. Syntax: is_readable(file)
  • 18. is_readable() function $file = "test.txt"; if(is_readable($file)){ echo ("$file is readable"); } else { echo ("$file is not readable"); }
  • 19. is_writable() function The is_writable() function checks whether the specified file is writeable. This function returns TRUE if the file is writeable. Syntax: is_writable(file)
  • 20. is_writable() function $file = "test.txt"; if(is_writable($file)) { echo ("$file is writeable"); } else { echo ("$file is not writeable"); }
  • 21. is_executable() function The is_executable() function checks whether the specified file is executable. This function returns TRUE if the file is executable. Syntax: is_executable(file)
  • 22. is_executable() function $file = "setup.exe"; if(is_executable($file)) { echo ("$file is executable"); } else { echo ("$file is not executable"); }
  • 23. filesize() function The filesize() function returns the size of the specified file. This function returns the file size in bytes on success or FALSE on failure. Syntax: filesize(filename)
  • 25. filemtime() function The filemtime() function returns the last time the file content was modified. This function returns the last change time as a Unix timestamp on success, FALSE on failure. Syntax: filemtime(filename)
  • 26. filemtime() function echo filemtime("test.txt"); echo "<br />"; echo "Last modified: ".date("F d Y H:i:s.",filemtime("test.txt"));
  • 27. filectime() function The filectime() function returns the last time the specified file was changed. This function returns the last change time as a Unix timestamp on success, FALSE on failure. Syntax: filectime(filename)
  • 28. filectime() function echo filectime("test.txt"); echo "<br />"; echo "Last change: ".date("F d Y H:i:s.",filectime("test.txt"));
  • 29. fileatime() function The fileatime() function returns the last access time of the specified file. This function returns the last access time as a Unix timestamp on success, FALSE on failure. Syntax: fileatime(filename)
  • 30. fileatime() function echo fileatime("test.txt"); echo "<br />"; echo "Last access: ".date("F d Y H:i:s.",fileatime("test.txt"));
  • 31. Creating and deleting files • touch() function • unlink() function
  • 32. touch() function The touch() function sets the access and modification time of the specified file. This function returns TRUE on success, or FALSE on failure. Syntax: touch(filename, time, atime)
  • 34. unlink() function The unlink() function deletes a file. This function returns TRUE on success, or FALSE on failure. Syntax: unlink(filename, context)
  • 35. unlink() function $file = "test.txt"; if (!unlink($file)) { echo ("Error deleting $file"); } else { echo ("Deleted $file"); }
  • 36. File reading, writing and appending • Open File - fopen() • Close File - fclose() • Read File - fread() • Read Single Line - fgets() • Check End-Of-File - feof() • Read Single Character - fgetc() • Seek File - fseek() • Write File - fwrite() • Write File - fputs() • Lock File - flock()
  • 37. Open File - fopen() The fopen() function opens a file or URL. If fopen() fails, it returns FALSE and an error on failure. Syntax: fopen(filename, mode, include_path, context)
  • 38. File open modes Modes Description r Open a file for read only. File pointer starts at the beginning of the file w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x Creates a new file for write only. Returns FALSE and an error if file already exists r+ Open a file for read/write. File pointer starts at the beginning of the file w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
  • 39. Open File - fopen() $file = fopen("test.txt","r"); $file = fopen("/home/test/test.txt","r"); $file = fopen("/home/test/test.gif","wb"); $file = fopen("http://www.example.com/","r"); $file = fopen("ftp://user:password@example.com/test.txt ","w");
  • 40. Close File - fclose() The fclose() function closes an open file. This function returns TRUE on success or FALSE on failure. Syntax: fclose(file)
  • 41. Close File - fclose() $file = fopen("test.txt","r"); //some code to be executed fclose($file);
  • 42. Read File - fread() The fread() reads from an open file. The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the read string, or FALSE on failure. Syntax: fread(file, length)
  • 43. Read File - fread() $file = fopen("test.txt","r"); fread($file, filesize("test.txt")); fclose($file);
  • 44. Read Single Line - fgets() The fgets() function returns a line from an open file. The fgets() function stops returning on a new line, at the specified length, or at EOF, whichever comes first. This function returns FALSE on failure. Syntax: fgets(file, length)
  • 45. Read Single Line - fgets() $file = fopen("test.txt","r"); echo fgets($file). "<br />"; fclose($file);
  • 46. Check End-Of-File - feof() The feof() function checks if the "end-of-file" (EOF) has been reached. This function returns TRUE if an error occurs, or if EOF has been reached. Otherwise it returns FALSE. Syntax: feof(file)
  • 47. Check End-Of-File - feof() $file = fopen("test.txt", "r"); //Output a line of the file until the end is reached while(! feof($file)) { echo fgets($file). "<br />"; } fclose($file);
  • 48. Read Single Character - fgetc() The fgetc() function returns a single character from an open file. Syntax: fgetc(file)
  • 49. Read Single Character - fgetc() $file = fopen("test2.txt", "r"); while (! feof ($file)) { echo fgetc($file); } fclose($file);
  • 50. Seek File - fseek() The fseek() function seeks in an open file. This function moves the file pointer from its current position to a new position, forward or backward, specified by the number of bytes. This function returns 0 on success, or -1 on failure. Seeking past EOF will not generate an error. Syntax: fseek(file, offset, whence)
  • 51. Seek File - fseek() $file = fopen("test.txt", "r"); // read first line fgets($file); // move back to beginning of file fseek($file, 0);
  • 52. Write File - fwrite() The fwrite() writes to an open file. The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the number of bytes written, or FALSE on failure. Syntax: fwrite(file, string, length)
  • 53. Write File - fwrite() $file = fopen("test.txt","w"); echo fwrite($file,"Hello World. Testing!"); fclose($file);
  • 54. Write File - fputs() The fputs() writes to an open file. The function will stop at the end of the file or when it reaches the specified length, whichever comes first. This function returns the number of bytes written on success, or FALSE on failure. Syntax: fputs(file, string, length)
  • 55. Write File - fputs() $file = fopen("test.txt","w"); echo fputs($file,"Hello World. Testing!"); fclose($file);
  • 56. Lock File - flock() The flock() function locks or releases a file. This function returns TRUE on success or FALSE on failure. Syntax: flock(file, lock, block)
  • 57. Lock File - flock() $file = fopen("test.txt", "w+"); if (flock($file, LOCK_EX)) { fwrite($file, "Write something"); flock($file, LOCK_UN); } else { echo "Error locking file!"; } fclose($file);
  • 58. Working with Directories • Create directory - mkdir() • Remove directory - rmdir() • Open directory - opendir() • Read directory - readdir()
  • 59. Create directory - mkdir() The mkdir() function creates a directory. This function returns TRUE on success, or FALSE on failure. Syntax: mkdir(path, mode, recursive, context)
  • 60. Create directory - mkdir() mkdir("testing", 0775);
  • 61. Remove directory - rmdir() The rmdir() function removes an empty directory. This function returns TRUE on success, or FALSE on failure. Syntax: rmdir(dir, context)
  • 62. Remove directory - rmdir() $path = "images"; if(!rmdir($path)) { echo ("Could not remove $path"); }
  • 63. Open directory - opendir() The opendir() function opens a directory handle. Syntax: opendir(path, context);
  • 64. Open directory - opendir() $dir = "images"; if ($dh = opendir($dir)){ echo "$dir directory opened"; } closedir($dh);
  • 65. Read directory - readdir() The readdir() function returns the name of the next entry in a directory. Syntax: readdir(dir_handle);
  • 66. Read directory - readdir() $dir = "images"; // Open a directory, and read its contents if (is_dir($dir)){ if ($dh = opendir($dir)){ while (($file = readdir($dh)) !== false){ echo "filename:" . $file . "<br>"; } closedir($dh); } }

Editor's Notes

  1. Note: The result of this function are cached. Use clearstatcache() to clear the cache.
  2. File modification time represents when the data blocks or content are changed or modified, not including that of meta data such as ownership or ownergroup.
  3. File change time represents the time when the meta data or inode data of a file is altered, such as the change of permissions, ownership or group.
  4. File change time represents the time when the meta data or inode data of a file is altered, such as the change of permissions, ownership or group.
  5. Note: The result of this function are cached. Use clearstatcache() to clear the cache.
  6. This function can be used to create a new file
  7. include_path Optional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream
  8. $file = fopen("/home/test/test.gif","wb"); //B for binary safe
  9. This function Advances internal pointer to the next line
  10. file Required. Specifies the open file to write to string Required. Specifies the string to write to the open file length Optional. Specifies the maximum number of bytes to write
  11. The fputs() function is an alias of the fwrite() function. file Required. Specifies the open file to write to string Required. Specifies the string to write to the open file length Optional. Specifies the maximum number of bytes to write
  12. Lock parameter - Required. Specifies what kind of lock to use.Possible values: LOCK_SH - Shared lock (reader). Allow other processes to access the file LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file LOCK_UN - Release a shared or exclusive lock LOCK_NB - Avoids blocking other processes while locking
  13. LOCK_SH - Shared lock (reader). Allow other processes to access the file LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file LOCK_UN - Release a shared or exclusive lock LOCK_NB - Avoids blocking other processes while locking
  14. mode Optional. Specifies permissions. By default, the mode is 0777 (widest possible access).The mode parameter consists of four numbers: The first number is always zero The second number specifies permissions for the owner The third number specifies permissions for the owner's user group The fourth number specifies permissions for everybody else Possible values (to set multiple permissions, add up the following numbers): 1 = execute permissions 2 = write permissions 4 = read permissions
  15. Returns the directory handle resource on success. FALSE on failure.