SlideShare une entreprise Scribd logo
1  sur  33
PHP Workshop 1
File Handling with PHP
PHP Workshop 2
Files and PHP
• File Handling
– Data Storage
• Though slower than a database
– Manipulating uploaded files
• From forms
– Creating Files for download
PHP Workshop 3
Open/Close a File
• A file is opened with fopen() as a “stream”,
and PHP returns a ‘handle’ to the file that
can be used to reference the open file in
other functions.
• Each file is opened in a particular mode.
• A file is closed with fclose() or when your
script ends.
PHP Workshop 4
File Open Modes
‘r’ Open for reading only. Start at beginning of
file.
‘r+’ Open for reading and writing. Start at
beginning of file.
‘w’ Open for writing only. Remove all previous
content, if file doesn’t exist, create it.
‘a’ Open writing, but start at END of current
content.
‘a+’ Open for reading and writing, start at END
and create file if necessary.
PHP Workshop 5
File Open/Close Example
<?php
// open file to read
$toread = fopen(‘some/file.ext’,’r’);
// open (possibly new) file to write
$towrite = fopen(‘some/file.ext’,’w’);
// close both files
fclose($toread);
fclose($towrite);
?>
PHP Workshop 6
Now what..?
• If you open a file to read, you can use
more in-built PHP functions to read data..
• If you open the file to write, you can use
more in-built PHP functions to write..
PHP Workshop 7
Reading Data
• There are two main functions to read data:
• fgets($handle,$bytes)
– Reads up to $bytes of data, stops at newline
or end of file (EOF)
• fread($handle,$bytes)
– Reads up to $bytes of data, stops at EOF.
PHP Workshop 8
Reading Data
• We need to be aware of the End Of File
(EOF) point..
• feof($handle)
– Whether the file has reached the EOF point.
Returns true if have reached EOF.
PHP Workshop 9
Data Reading Example
$handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}
fclose($handle);
PHP Workshop 10
Data Reading Example
$handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}
fclose($handle);
Open the file and assign the resource to $handle
$handle = fopen('people.txt', 'r');
PHP Workshop 11
Data Reading Example
$handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}
fclose($handle);
While NOT at the end of the file, pointed
to by $handle,
get and echo the data line by line
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}
PHP Workshop 12
Data Reading Example
$handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
}
fclose($handle);
Close the file
fclose($handle);
PHP Workshop 13
File Open shortcuts..
• There are two ‘shortcut’ functions that don’t
require a file to be opened:
• $lines = file($filename)
– Reads entire file into an array with each line a
separate entry in the array.
• $str = file_get_contents($filename)
– Reads entire file into a single string.
PHP Workshop 14
Writing Data
• To write data to a file use:
• fwrite($handle,$data)
– Write $data to the file.
PHP Workshop 15
Data Writing Example
$handle = fopen('people.txt', 'a');
fwrite($handle, “nFred:Male”);
fclose($handle);
PHP Workshop 16
Data Writing Example
$handle = fopen('people.txt', 'a');
fwrite($handle, 'nFred:Male');
fclose($handle);
$handle = fopen('people.txt', 'a');
Open file to append data (mode 'a')
fwrite($handle, “nFred:Male”);
Write new data (with line
break after previous data)
PHP Workshop 17
Other File Operations
• Delete file
– unlink('filename');
• Rename (file or directory)
– rename('old name', 'new name');
• Copy file
– copy('source', 'destination');
• And many, many more!
– www.php.net/manual/en/ref.filesystem.php
PHP Workshop 18
Dealing With Directories
• Open a directory
– $handle = opendir('dirname');
• $handle 'points' to the directory
• Read contents of directory
– readdir($handle)
• Returns name of next file in directory
• Files are sorted as on filesystem
• Close a directory
– closedir($handle)
• Closes directory 'stream'
PHP Workshop 19
Directory Example
$handle = opendir('./');
while(false !== ($file=readdir($handle)))
{
echo "$file<br />";
}
closedir($handle);
PHP Workshop 20
Directory Example
$handle = opendir('./');
while(false !== ($file=readdir($handle)))
{
echo "$file<br />";
}
closedir($handle);
Open current directory
$handle = opendir('./');
PHP Workshop 21
Directory Example
$handle = opendir('./');
while(false !== ($file=readdir($handle)))
{
echo "$file<br />";
}
closedir($handle);
Whilst readdir() returns a name, loop
through directory contents, echoing
results
while(false !== ($file=readdir($handle)))
{
echo "$file<br />";
}
PHP Workshop 22
Directory Example
$handle = opendir('./');
while(false !== ($file=readdir($handle)))
{
echo "$file<br />";
}
closedir($handle);
Close the directory stream
closedir($handle);
PHP Workshop 23
Other Directory Operations
• Get current directory
– getcwd()
• Change Directory
– chdir('dirname');
• Create directory
– mkdir('dirname');
• Delete directory (MUST be empty)
– rmdir('dirname');
• And more!
– www.php.net/manual/en/ref.dir.php
PHP Workshop 24
Review
• Can open and close files.
• Can read a file line by line or all at one go.
• Can write to files.
• Can open and cycle through the files in a
directory.
PHP Workshop 25
Review all
• Create a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or
die('Cannot open file: '.$my_file);
//implicitly creates file
PHP Workshop 26
Review all
• Open a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or
die('Cannot open file: '.$my_file); //open
file for writing ('w','r','a')...
PHP Workshop 27
Review all
• Read a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));
PHP Workshop 28
Review all
• Write to a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or
die('Cannot open file: '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);
PHP Workshop 29
Review all
• Append to a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot
open file: '.$my_file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "n".'New data line 2';
fwrite($handle, $new_data);
PHP Workshop 30
Review all
• Close a File
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or
die('Cannot open file: '.$my_file);
//write some data here
fclose($handle);
PHP Workshop 31
Review all
• Delete a File
$my_file = 'file.txt';
unlink($my_file);
PHP Workshop 32
Review all
PHP Workshop 33
Review all

Contenu connexe

Tendances

Tendances (19)

Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHP
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handling
 
File upload for the 21st century
File upload for the 21st centuryFile upload for the 21st century
File upload for the 21st century
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c language
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
Fileinc
FileincFileinc
Fileinc
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHPQuick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHP
 
.Net (F # ) Records, lists
.Net (F # ) Records, lists.Net (F # ) Records, lists
.Net (F # ) Records, lists
 
Presentation on files
Presentation on filesPresentation on files
Presentation on files
 
05 File Handling Upload Mysql
05 File Handling Upload Mysql05 File Handling Upload Mysql
05 File Handling Upload Mysql
 
PHP file
PHP  filePHP  file
PHP file
 
File in C programming
File in C programmingFile in C programming
File in C programming
 
Assic 16th Lecture
Assic 16th LectureAssic 16th Lecture
Assic 16th Lecture
 
Unix lab manual
Unix lab manualUnix lab manual
Unix lab manual
 
Unix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU KarnatakaUnix 1st sem lab programs a - VTU Karnataka
Unix 1st sem lab programs a - VTU Karnataka
 
TDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streamsTDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streams
 
scdevsumit 2016 - Become a jedi with php streams
scdevsumit 2016 - Become a jedi with php streamsscdevsumit 2016 - Become a jedi with php streams
scdevsumit 2016 - Become a jedi with php streams
 
File include
File includeFile include
File include
 
Image upload in php MySql
Image upload in php MySqlImage upload in php MySql
Image upload in php MySql
 

En vedette

Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Ley de protección a los animales il00000158 texto completo
Ley de protección a los animales   il00000158 texto completoLey de protección a los animales   il00000158 texto completo
Ley de protección a los animales il00000158 texto completoLiz Churqui
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Muhamad Al Imran
 

En vedette (9)

Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Discussion 2 q
Discussion 2 qDiscussion 2 q
Discussion 2 q
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Discussion2 tips
Discussion2 tipsDiscussion2 tips
Discussion2 tips
 
Ley de protección a los animales il00000158 texto completo
Ley de protección a los animales   il00000158 texto completoLey de protección a los animales   il00000158 texto completo
Ley de protección a los animales il00000158 texto completo
 
Discussion 1 q
Discussion 1 qDiscussion 1 q
Discussion 1 q
 
Lab5 tips
Lab5 tipsLab5 tips
Lab5 tips
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 

Similaire à Php i basic chapter 4 (20)

Files
FilesFiles
Files
 
Files
FilesFiles
Files
 
Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
Php files
Php filesPhp files
Php files
 
PHP File Handling
PHP File Handling PHP File Handling
PHP File Handling
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Chap 5 php files part 1
Chap 5 php files part 1Chap 5 php files part 1
Chap 5 php files part 1
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
PHP Filing
PHP Filing PHP Filing
PHP Filing
 
Files and Directories in PHP
Files and Directories in PHPFiles and Directories in PHP
Files and Directories in PHP
 
Php hacku
Php hackuPhp hacku
Php hacku
 
PHP Without PHP—Confoo
PHP Without PHP—ConfooPHP Without PHP—Confoo
PHP Without PHP—Confoo
 
lecture 10.pptx
lecture 10.pptxlecture 10.pptx
lecture 10.pptx
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHP
 
File in C language
File in C languageFile in C language
File in C language
 
File handling-c
File handling-cFile handling-c
File handling-c
 
PHP for hacks
PHP for hacksPHP for hacks
PHP for hacks
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 

Dernier

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 

Dernier (20)

Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 

Php i basic chapter 4

  • 1. PHP Workshop 1 File Handling with PHP
  • 2. PHP Workshop 2 Files and PHP • File Handling – Data Storage • Though slower than a database – Manipulating uploaded files • From forms – Creating Files for download
  • 3. PHP Workshop 3 Open/Close a File • A file is opened with fopen() as a “stream”, and PHP returns a ‘handle’ to the file that can be used to reference the open file in other functions. • Each file is opened in a particular mode. • A file is closed with fclose() or when your script ends.
  • 4. PHP Workshop 4 File Open Modes ‘r’ Open for reading only. Start at beginning of file. ‘r+’ Open for reading and writing. Start at beginning of file. ‘w’ Open for writing only. Remove all previous content, if file doesn’t exist, create it. ‘a’ Open writing, but start at END of current content. ‘a+’ Open for reading and writing, start at END and create file if necessary.
  • 5. PHP Workshop 5 File Open/Close Example <?php // open file to read $toread = fopen(‘some/file.ext’,’r’); // open (possibly new) file to write $towrite = fopen(‘some/file.ext’,’w’); // close both files fclose($toread); fclose($towrite); ?>
  • 6. PHP Workshop 6 Now what..? • If you open a file to read, you can use more in-built PHP functions to read data.. • If you open the file to write, you can use more in-built PHP functions to write..
  • 7. PHP Workshop 7 Reading Data • There are two main functions to read data: • fgets($handle,$bytes) – Reads up to $bytes of data, stops at newline or end of file (EOF) • fread($handle,$bytes) – Reads up to $bytes of data, stops at EOF.
  • 8. PHP Workshop 8 Reading Data • We need to be aware of the End Of File (EOF) point.. • feof($handle) – Whether the file has reached the EOF point. Returns true if have reached EOF.
  • 9. PHP Workshop 9 Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle);
  • 10. PHP Workshop 10 Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); Open the file and assign the resource to $handle $handle = fopen('people.txt', 'r');
  • 11. PHP Workshop 11 Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); While NOT at the end of the file, pointed to by $handle, get and echo the data line by line while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; }
  • 12. PHP Workshop 12 Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); Close the file fclose($handle);
  • 13. PHP Workshop 13 File Open shortcuts.. • There are two ‘shortcut’ functions that don’t require a file to be opened: • $lines = file($filename) – Reads entire file into an array with each line a separate entry in the array. • $str = file_get_contents($filename) – Reads entire file into a single string.
  • 14. PHP Workshop 14 Writing Data • To write data to a file use: • fwrite($handle,$data) – Write $data to the file.
  • 15. PHP Workshop 15 Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, “nFred:Male”); fclose($handle);
  • 16. PHP Workshop 16 Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, 'nFred:Male'); fclose($handle); $handle = fopen('people.txt', 'a'); Open file to append data (mode 'a') fwrite($handle, “nFred:Male”); Write new data (with line break after previous data)
  • 17. PHP Workshop 17 Other File Operations • Delete file – unlink('filename'); • Rename (file or directory) – rename('old name', 'new name'); • Copy file – copy('source', 'destination'); • And many, many more! – www.php.net/manual/en/ref.filesystem.php
  • 18. PHP Workshop 18 Dealing With Directories • Open a directory – $handle = opendir('dirname'); • $handle 'points' to the directory • Read contents of directory – readdir($handle) • Returns name of next file in directory • Files are sorted as on filesystem • Close a directory – closedir($handle) • Closes directory 'stream'
  • 19. PHP Workshop 19 Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo "$file<br />"; } closedir($handle);
  • 20. PHP Workshop 20 Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo "$file<br />"; } closedir($handle); Open current directory $handle = opendir('./');
  • 21. PHP Workshop 21 Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo "$file<br />"; } closedir($handle); Whilst readdir() returns a name, loop through directory contents, echoing results while(false !== ($file=readdir($handle))) { echo "$file<br />"; }
  • 22. PHP Workshop 22 Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo "$file<br />"; } closedir($handle); Close the directory stream closedir($handle);
  • 23. PHP Workshop 23 Other Directory Operations • Get current directory – getcwd() • Change Directory – chdir('dirname'); • Create directory – mkdir('dirname'); • Delete directory (MUST be empty) – rmdir('dirname'); • And more! – www.php.net/manual/en/ref.dir.php
  • 24. PHP Workshop 24 Review • Can open and close files. • Can read a file line by line or all at one go. • Can write to files. • Can open and cycle through the files in a directory.
  • 25. PHP Workshop 25 Review all • Create a File $my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
  • 26. PHP Workshop 26 Review all • Open a File $my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //open file for writing ('w','r','a')...
  • 27. PHP Workshop 27 Review all • Read a File $my_file = 'file.txt'; $handle = fopen($my_file, 'r'); $data = fread($handle,filesize($my_file));
  • 28. PHP Workshop 28 Review all • Write to a File $my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); $data = 'This is the data'; fwrite($handle, $data);
  • 29. PHP Workshop 29 Review all • Append to a File $my_file = 'file.txt'; $handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file); $data = 'New data line 1'; fwrite($handle, $data); $new_data = "n".'New data line 2'; fwrite($handle, $new_data);
  • 30. PHP Workshop 30 Review all • Close a File $my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //write some data here fclose($handle);
  • 31. PHP Workshop 31 Review all • Delete a File $my_file = 'file.txt'; unlink($my_file);