SlideShare a Scribd company logo
Chapter 3
File Handling
6/17/2023 1
Contents
• Files and Directories
• Write to Files
• Read from Files
• Create Directories
• Upload Files
• Rename and Delete Files and Directories
6/17/2023 2
PHP File Handling
• File handling is an important part of any web
application.
• You often need to open and process a file for
different tasks.
• PHP has several functions for creating, reading,
and editing files.
• The files can be .doc file, .txt file, .xml file any
kind of file supports all php function for
manipulate files.
6/17/2023 3
PHP File Open and Read
• how to open file , read file and close file using
file handling functions:
1. fopen() – open file
2. fread() – read file
3. fclose() – close file
6/17/2023 4
PHP Create File - fopen()
• The fopen() function is used to create a file..
• If you use fopen() on a file that does not exist, it
will create it.
• The example below creates a new file called
"testfile.txt".
• The file will be created in the same directory
where the PHP code resides:
$myfile = fopen("testfile.txt", "w");
6/17/2023 5
File functions The use of functions
touch() used to create a file.
unlink() used to delete a file.
copy() used to copy a file.
rename() used to rename a file.
file_exists() used to check whether the file exists or not.
filesize() used to check size of file.
realpath() used to check real path of file.
fopen() used to open existing file.
fread() used to reads from an pen file.
fwrite() used to write to file.
fclose() used to close an open file.
fgets() used to read a single line from a file.
fgetc() used to read a single character from a file.
feof() used to check ‘end of file’.
6/17/2023 6
PHP fopen() function
• PHP fopen() function used to open a file. If file
does not exist then fopen() function will create
a new file.
• The fopen() function must use with mode
character like ‘w’, ‘a’ ,’r’ etc.
<?php
fopen(“filename with extension”, “mode char”);
?>
6/17/2023 7
6/17/2023 8
Example - fopen()
<?php
//open text file
fopen("abc.txt","w");
//open ms word .doc file
fopen("abc.doc","w");
//open pdf file
fopen('abc.pdf',"w");
?>
6/17/2023 9
PHP Read File - fread()
• The fread() function reads from an open file.
• The first parameter of fread() contains the
name of the file to read from and the second
parameter specifies the maximum number of
bytes to read.
• fread($myfile,filesize("webdictionary.txt"));
6/17/2023 10
Example
• <!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable
to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
6/17/2023 11
PHP close file – fclose()
• The fclose() function is used to close an open
file.
• PHP fclose() syntax
<?php
fclose(“filename”);
?>
6/17/2023 12
PHP File Create and Write
• how to create a file and how to write to a file
on the server.
• Create a File – touch() ,
• Create a File, if does not exist – fopen()
• Write to a File – fwrite()
6/17/2023 13
touch() and fopen()
<?php
//create text file
touch("abc.txt");
//create ms word .doc
file
touch("abc.doc");
//create pdf file
touch('abc.pdf');
?>
<?php
//create text file
fopen("abc.txt","w");
//create word .doc file
fopen("abc.doc","w");
//create pdf file
fopen('abc.pdf',"w");
?>
6/17/2023 14
PHP Write to File - fwrite()
• The fwrite() function is used to write to a file.
• The first parameter of fwrite() contains the
name of the file to write to and the second
parameter is the string to be written.
• The example below writes a couple of names
into a new file called "newfile.txt":
6/17/2023 15
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable
to open file!");
$txt = "John Doen";
fwrite($myfile, $txt);
$txt = "Jane Doen";
fwrite($myfile, $txt);
fclose($myfile);
?>
6/17/2023 16
• <?php
//open file abc.txt
$myfile = fopen("abc.txt", "w");
$text = "Meera Academy";
fwrite($myfile, $text);
fclose($myfile);
?>
6/17/2023 17
PHP form example of fwrite()
<html>
<body>
<FORM method="POST">
Enter String : <input type="text" name="name">
<br/> <br/>
<input type="submit" name="Submit1"
value="Write File">
</FORM>
6/17/2023 18
Cont…
<?php
if(isset($_POST['Submit1'])) {
//open file abc.txt in append mode
$myfile = fopen("abc.txt", "a");
$text = $_POST["name"];
fwrite($myfile, $text);
fclose($myfile); }
?> </body> </html>
6/17/2023 19
PHP Close File - fclose()
• The fclose() function is used to close an open
file.
• It's a good programming practice to close all
files after you have finished with them.
• The fclose() requires the name of the file (or a
variable that holds the filename) we want to
close:
6/17/2023 20
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
6/17/2023 21
PHP Check End-Of-File - feof()
• The feof() function checks if the "end-of-file" (EOF)
has been reached.
• The example below reads the "webdictionary.txt" file
line by line, until end-of-file is reached:
<?php
$file = fopen("abc.txt", "r");
while(! feof($file)) {
echo fgets($file). "<br>";
}
fclose($file);
?>
6/17/2023 22
PHP Read Single Character - fgetc()
• The fgetc() function is used to read a single
character from a file.
<?php
$myfile =
fopen("webdictionary.txt", "r") or die("Unable to
open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
6/17/2023 23
PHP copy() Function
• The copy() function copies a file.
• Note: If the to_file file already exists, it will be
overwritten.
• Syntax
copy(from_file, to_file, context)
<?php
Echo copy("webdictionary.doc","studMark.doc");
?>
6/17/2023 24
unlink() Function
• Delete a file:
<?php
unlink("stud.doc");
?>
6/17/2023 25
PHP file_exists() Function
• The file_exists() function checks whether a file
or directory exists.
Syntax
file_exists(path)
• Check whether a file exists:
<?php
echo file_exists(“stud1.txt");
?>
6/17/2023 26
filesize() Function
• The filesize() function returns the size of a file.
• Return the file size for "test.txt":
<?php
echo filesize("test.txt");
?>
6/17/2023 27
PHP File Inclusion
• PHP has two function which can used to
include one PHP file into another PHP file
before the server executes it.
1. The include() function
2. The require() function
• For the designing purpose in web forms the
same header, footer or menu displayed on all
web pages of website.
6/17/2023 28
• Programmer has to design same menu on
multiple pages, if changes required in future it
will very complicated to open all pages then make
change on all pages.
• for resolving this problem we use include and
require function in php.
• Just design menu or header in one php page and
display same menu on multiple pages using
include function.
• if changes required on menu.php page, it will
make effect on all other pages automatically.
6/17/2023 29
The include() function
• The include function copy all text of one PHP
file into another PHP file that used the include
statement.
• The include function used when we use same
menu or header on multiple pages of a
website.
• PHP include() syntax:
include ‘ filename’;
6/17/2023 30
Example1
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " Infolink.com</p>";
?>
footer.php
6/17/2023 31
Example2
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML
Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript
Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home
page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>
Assume we have a standard menu file called
"menu.php":
6/17/2023 32
Example3
<?php
$color='red';
$car='BMW';
?>
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'vars.php';
echo "I have a $color $car.";
?>
</body>
</html>
Assume we have a file called
"vars.php", with some variables
defined:
Then, if we include the "vars.php" file, the
variables can be used in the calling file:
6/17/2023 33
PHP include Example
• We have a same header for all website pages so
create “header.php” file like:
<?php
echo "<h1> Welcomme
Meera Academy
</h1>";
?>
<html>
<body>
<?php include 'header.php'; ?>
<p>The first page of site</p>
</body>
</html>
6/17/2023 34
Example-2
Menu.php
<?php echo '<ul><li><a
href="home.com">HOME</a></li> <li><a
href="php.com">PHP</a></li> <li><a
href="asp.com">ASP.NET</a></li> <li><a
href="project.com">PROJECTS</a></li></ul>';
?>
6/17/2023 35
<html>
<head>
<title>PHP include Example</title>
</head>
<body>
<?php include 'menu.php'; ?>
<p>The first page of site</p>
</body>
</html>
6/17/2023 36
The PHP require() Function
• The require() function copy all the text from one
php file into another php file that uses the
require() function.
• In require() function there is a problem with file
then the require() function generate fatal error
and stop execution of code.
• while the include() function will continue to
execute script.
• The require() function is better than the include()
function, because scripts not to be continue if file
has problem or missing.
6/17/2023 37

More Related Content

What's hot

Cascading style sheet
Cascading style sheetCascading style sheet
Cascading style sheet
Michael Jhon
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
Maruf Abdullah (Rion)
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
Nisa Soomro
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
Gil Fink
 
Introduction to xhtml
Introduction to xhtmlIntroduction to xhtml
Introduction to xhtmlDhairya Joshi
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
Mindfire Solutions
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
Nisa Soomro
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
Spy Seat
 
Web technology lab manual
Web technology lab manualWeb technology lab manual
Web technology lab manual
neela madheswari
 
Html coding
Html codingHtml coding
Html coding
Briana VanBuskirk
 
Php technical presentation
Php technical presentationPhp technical presentation
Php technical presentation
dharmendra kumar dhakar
 
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORS
Vladimir Dzhuvinov
 
Css selectors
Css selectorsCss selectors
Css selectors
Dinesh Kumar
 

What's hot (20)

Cascading style sheet
Cascading style sheetCascading style sheet
Cascading style sheet
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Php basics
Php basicsPhp basics
Php basics
 
Introduction to xhtml
Introduction to xhtmlIntroduction to xhtml
Introduction to xhtml
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
 
Web technology lab manual
Web technology lab manualWeb technology lab manual
Web technology lab manual
 
Html coding
Html codingHtml coding
Html coding
 
Php ppt
Php pptPhp ppt
Php ppt
 
Php technical presentation
Php technical presentationPhp technical presentation
Php technical presentation
 
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORS
 
Css selectors
Css selectorsCss selectors
Css selectors
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 

Similar to PHP File Handling

Files in PHP.pptx g
Files in PHP.pptx                      gFiles in PHP.pptx                      g
Files in PHP.pptx g
FiromsaDine
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
Rasan Samarasinghe
 
Php files
Php filesPhp files
Php files
kalyani66
 
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
 
Php advance
Php advancePhp advance
Php advance
Rattanjeet Singh
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operationsmussawir20
 
File management
File managementFile management
File management
sumathiv9
 
PHP Filing
PHP Filing PHP Filing
PHP Filing
Nisa Soomro
 
Php mysql
Php mysqlPhp mysql
Php mysql
Ajit Yadav
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
Jamshid Hashimi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
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
 
File operations
File operationsFile operations
File operations
PrabhatKumarChaudhar2
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
VrushaliSolanke
 
9780538745840 ppt ch05
9780538745840 ppt ch059780538745840 ppt ch05
9780538745840 ppt ch05
Terry Yoast
 
4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptx4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptx
MasSam13
 
PHP file handling
PHP file handling PHP file handling
PHP file handling
wahidullah mudaser
 
File system
File systemFile system
File system
Gayane Aslanyan
 

Similar to PHP File Handling (20)

Files in PHP.pptx g
Files in PHP.pptx                      gFiles in PHP.pptx                      g
Files in PHP.pptx g
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
 
Php files
Php filesPhp files
Php files
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3
 
Php advance
Php advancePhp advance
Php advance
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
File management
File managementFile management
File management
 
PHP Filing
PHP Filing PHP Filing
PHP Filing
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Files nts
Files ntsFiles nts
Files nts
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
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
 
File operations
File operationsFile operations
File operations
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
9780538745840 ppt ch05
9780538745840 ppt ch059780538745840 ppt ch05
9780538745840 ppt ch05
 
4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptx4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptx
 
PHP file handling
PHP file handling PHP file handling
PHP file handling
 
File system
File systemFile system
File system
 

Recently uploaded

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 

Recently uploaded (20)

Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 

PHP File Handling

  • 2. Contents • Files and Directories • Write to Files • Read from Files • Create Directories • Upload Files • Rename and Delete Files and Directories 6/17/2023 2
  • 3. PHP File Handling • File handling is an important part of any web application. • You often need to open and process a file for different tasks. • PHP has several functions for creating, reading, and editing files. • The files can be .doc file, .txt file, .xml file any kind of file supports all php function for manipulate files. 6/17/2023 3
  • 4. PHP File Open and Read • how to open file , read file and close file using file handling functions: 1. fopen() – open file 2. fread() – read file 3. fclose() – close file 6/17/2023 4
  • 5. PHP Create File - fopen() • The fopen() function is used to create a file.. • If you use fopen() on a file that does not exist, it will create it. • The example below creates a new file called "testfile.txt". • The file will be created in the same directory where the PHP code resides: $myfile = fopen("testfile.txt", "w"); 6/17/2023 5
  • 6. File functions The use of functions touch() used to create a file. unlink() used to delete a file. copy() used to copy a file. rename() used to rename a file. file_exists() used to check whether the file exists or not. filesize() used to check size of file. realpath() used to check real path of file. fopen() used to open existing file. fread() used to reads from an pen file. fwrite() used to write to file. fclose() used to close an open file. fgets() used to read a single line from a file. fgetc() used to read a single character from a file. feof() used to check ‘end of file’. 6/17/2023 6
  • 7. PHP fopen() function • PHP fopen() function used to open a file. If file does not exist then fopen() function will create a new file. • The fopen() function must use with mode character like ‘w’, ‘a’ ,’r’ etc. <?php fopen(“filename with extension”, “mode char”); ?> 6/17/2023 7
  • 9. Example - fopen() <?php //open text file fopen("abc.txt","w"); //open ms word .doc file fopen("abc.doc","w"); //open pdf file fopen('abc.pdf',"w"); ?> 6/17/2023 9
  • 10. PHP Read File - fread() • The fread() function reads from an open file. • The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read. • fread($myfile,filesize("webdictionary.txt")); 6/17/2023 10
  • 11. Example • <!DOCTYPE html> <html> <body> <?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary.txt")); fclose($myfile); ?> </body> </html> 6/17/2023 11
  • 12. PHP close file – fclose() • The fclose() function is used to close an open file. • PHP fclose() syntax <?php fclose(“filename”); ?> 6/17/2023 12
  • 13. PHP File Create and Write • how to create a file and how to write to a file on the server. • Create a File – touch() , • Create a File, if does not exist – fopen() • Write to a File – fwrite() 6/17/2023 13
  • 14. touch() and fopen() <?php //create text file touch("abc.txt"); //create ms word .doc file touch("abc.doc"); //create pdf file touch('abc.pdf'); ?> <?php //create text file fopen("abc.txt","w"); //create word .doc file fopen("abc.doc","w"); //create pdf file fopen('abc.pdf',"w"); ?> 6/17/2023 14
  • 15. PHP Write to File - fwrite() • The fwrite() function is used to write to a file. • The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written. • The example below writes a couple of names into a new file called "newfile.txt": 6/17/2023 15
  • 16. <?php $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "John Doen"; fwrite($myfile, $txt); $txt = "Jane Doen"; fwrite($myfile, $txt); fclose($myfile); ?> 6/17/2023 16
  • 17. • <?php //open file abc.txt $myfile = fopen("abc.txt", "w"); $text = "Meera Academy"; fwrite($myfile, $text); fclose($myfile); ?> 6/17/2023 17
  • 18. PHP form example of fwrite() <html> <body> <FORM method="POST"> Enter String : <input type="text" name="name"> <br/> <br/> <input type="submit" name="Submit1" value="Write File"> </FORM> 6/17/2023 18
  • 19. Cont… <?php if(isset($_POST['Submit1'])) { //open file abc.txt in append mode $myfile = fopen("abc.txt", "a"); $text = $_POST["name"]; fwrite($myfile, $text); fclose($myfile); } ?> </body> </html> 6/17/2023 19
  • 20. PHP Close File - fclose() • The fclose() function is used to close an open file. • It's a good programming practice to close all files after you have finished with them. • The fclose() requires the name of the file (or a variable that holds the filename) we want to close: 6/17/2023 20
  • 21. <?php $myfile = fopen("webdictionary.txt", "r"); // some code to be executed.... fclose($myfile); ?> 6/17/2023 21
  • 22. PHP Check End-Of-File - feof() • The feof() function checks if the "end-of-file" (EOF) has been reached. • The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached: <?php $file = fopen("abc.txt", "r"); while(! feof($file)) { echo fgets($file). "<br>"; } fclose($file); ?> 6/17/2023 22
  • 23. PHP Read Single Character - fgetc() • The fgetc() function is used to read a single character from a file. <?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); // Output one character until end-of-file while(!feof($myfile)) { echo fgetc($myfile); } fclose($myfile); ?> 6/17/2023 23
  • 24. PHP copy() Function • The copy() function copies a file. • Note: If the to_file file already exists, it will be overwritten. • Syntax copy(from_file, to_file, context) <?php Echo copy("webdictionary.doc","studMark.doc"); ?> 6/17/2023 24
  • 25. unlink() Function • Delete a file: <?php unlink("stud.doc"); ?> 6/17/2023 25
  • 26. PHP file_exists() Function • The file_exists() function checks whether a file or directory exists. Syntax file_exists(path) • Check whether a file exists: <?php echo file_exists(“stud1.txt"); ?> 6/17/2023 26
  • 27. filesize() Function • The filesize() function returns the size of a file. • Return the file size for "test.txt": <?php echo filesize("test.txt"); ?> 6/17/2023 27
  • 28. PHP File Inclusion • PHP has two function which can used to include one PHP file into another PHP file before the server executes it. 1. The include() function 2. The require() function • For the designing purpose in web forms the same header, footer or menu displayed on all web pages of website. 6/17/2023 28
  • 29. • Programmer has to design same menu on multiple pages, if changes required in future it will very complicated to open all pages then make change on all pages. • for resolving this problem we use include and require function in php. • Just design menu or header in one php page and display same menu on multiple pages using include function. • if changes required on menu.php page, it will make effect on all other pages automatically. 6/17/2023 29
  • 30. The include() function • The include function copy all text of one PHP file into another PHP file that used the include statement. • The include function used when we use same menu or header on multiple pages of a website. • PHP include() syntax: include ‘ filename’; 6/17/2023 30
  • 31. Example1 <html> <body> <h1>Welcome to my home page!</h1> <p>Some text.</p> <p>Some more text.</p> <?php include 'footer.php';?> </body> </html> <?php echo "<p>Copyright &copy; 1999-" . date("Y") . " Infolink.com</p>"; ?> footer.php 6/17/2023 31
  • 32. Example2 <?php echo '<a href="/default.asp">Home</a> - <a href="/html/default.asp">HTML Tutorial</a> - <a href="/css/default.asp">CSS Tutorial</a> - <a href="/js/default.asp">JavaScript Tutorial</a> - <a href="default.asp">PHP Tutorial</a>'; ?> <html> <body> <div class="menu"> <?php include 'menu.php';?> </div> <h1>Welcome to my home page!</h1> <p>Some text.</p> <p>Some more text.</p> </body> </html> Assume we have a standard menu file called "menu.php": 6/17/2023 32
  • 33. Example3 <?php $color='red'; $car='BMW'; ?> <html> <body> <h1>Welcome to my home page!</h1> <?php include 'vars.php'; echo "I have a $color $car."; ?> </body> </html> Assume we have a file called "vars.php", with some variables defined: Then, if we include the "vars.php" file, the variables can be used in the calling file: 6/17/2023 33
  • 34. PHP include Example • We have a same header for all website pages so create “header.php” file like: <?php echo "<h1> Welcomme Meera Academy </h1>"; ?> <html> <body> <?php include 'header.php'; ?> <p>The first page of site</p> </body> </html> 6/17/2023 34
  • 35. Example-2 Menu.php <?php echo '<ul><li><a href="home.com">HOME</a></li> <li><a href="php.com">PHP</a></li> <li><a href="asp.com">ASP.NET</a></li> <li><a href="project.com">PROJECTS</a></li></ul>'; ?> 6/17/2023 35
  • 36. <html> <head> <title>PHP include Example</title> </head> <body> <?php include 'menu.php'; ?> <p>The first page of site</p> </body> </html> 6/17/2023 36
  • 37. The PHP require() Function • The require() function copy all the text from one php file into another php file that uses the require() function. • In require() function there is a problem with file then the require() function generate fatal error and stop execution of code. • while the include() function will continue to execute script. • The require() function is better than the include() function, because scripts not to be continue if file has problem or missing. 6/17/2023 37