SlideShare une entreprise Scribd logo
1  sur  20
PHP File Operations
Jamshid Hashimi
Trainer, Cresco Solution
http://www.jamshidhashimi.com
jamshid@netlinks.af
@jamshidhashimi
ajamshidhashimi
Afghanistan Workforce
Development Program
Agenda
• Introduction
• Creating a File
• Opening a File
– fopen()
• Reading From a File
– fgets()
• Writing to File
– fwrite()
• Removing File
– unlink()
• Appending Data
• File Locking
– flock()
Agenda
• Uploading Files via an HTML Form
• Getting File Information
• More File Functions
• Directory Functions
• Getting a Directory Listing
Introduction
• Manipulating files is a basic necessity for
serious programmers and PHP gives you a
great deal of tools for creating, uploading, and
editing files.
• This is one of the most fundamental subjects
of server side programming in general. Files
are used in web applications of all sizes.
Creating a File
• In PHP the fopen function is used to open
files. However, it can also create a file if it does
not find the file specified in the function call.
So if you use fopen on a file that does not
exist, it will create it, given that you open the
file for writing or appending.
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w')
or die("can't open file");
fclose($ourFileHandle);
File Operations Mode
Opening a File
• The fopen() function is used to open files in
PHP.
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to
open file!");
fclose($file);
Reading From a File
• The fgets() function is used to read a single
line from a file.
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to
open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br>";
}
fclose($file);
Writing to a File
• We can use php to write to a text file. The
fwrite function allows data to be written to
any type of file.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't
open file");
$stringData = "Kabul is the capitaln";
fwrite($fh, $stringData);
$stringData = "Samangan is a provincen";
fwrite($fh, $stringData);
fclose($fh);
Removing File
• In PHP you delete files by calling the unlink
function.
$myFile = "testFile.txt";
unlink($myFile);
Appending Data
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2n";
fwrite($fh, $stringData);
fclose($fh);
File Locking
• The key problem with file system operations is
the situation you are in if two scripts attempt
to write to a file at the same time.
• The fopen() function, when called on a
file, does not stop that same file from being
opened by another script.
File Locking
• LOCK_SH to acquire a shared lock (reader).
• LOCK_EX to acquire an exclusive lock (writer).
• LOCK_UN to release a lock (shared or
exclusive).
$fp = fopen( $filename,"w"); // open it for
WRITING ("w")
if (flock($fp, LOCK_EX)) {
// do your file writes here
flock($fp, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock
obtained
print "Could not lock $filename!n";
}
Uploading Files via an HTML Form
• With PHP, it is possible to upload files to the
server.
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file"
id="file"><br>
<input type="submit" name="submit"
value="Submit">
</form>
</body>
</html>
Uploading Files via an HTML Form
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . "
kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
Uploading Files via an HTML Form
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
Directory Functions
• scandir()
• getcwd()
<?php
print_r(scandir(”projects"));
?>
<?php
echo getcwd();
?>
Directory Functions
• chdir()
– The chdir() function changes the current directory
to the specified directory.
<?php
//Get current directory
echo getcwd();
echo "<br />";
//Change to the images directory
chdir(”projects");
echo "<br />";
echo getcwd();
DEMO
QUESTIONS?

Contenu connexe

Tendances (20)

Php array
Php arrayPhp array
Php array
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
Php basics
Php basicsPhp basics
Php basics
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Android activity lifecycle
Android activity lifecycleAndroid activity lifecycle
Android activity lifecycle
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
File system structure
File system structureFile system structure
File system structure
 
Computer Network Unit I RGPV
Computer Network Unit I RGPV Computer Network Unit I RGPV
Computer Network Unit I RGPV
 
Php
PhpPhp
Php
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
Php string function
Php string function Php string function
Php string function
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 

En vedette

En vedette (18)

Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
PHP 5 Magic Methods
PHP 5 Magic MethodsPHP 5 Magic Methods
PHP 5 Magic Methods
 
Chapter 08 php advance
Chapter 08   php advanceChapter 08   php advance
Chapter 08 php advance
 
P2P Networks
P2P NetworksP2P Networks
P2P Networks
 
File Uploading in PHP
File Uploading in PHPFile Uploading in PHP
File Uploading in PHP
 
php file uploading
php file uploadingphp file uploading
php file uploading
 
Music Downloading Website (HTML,CSS,PHP Presentation)
Music Downloading Website (HTML,CSS,PHP Presentation)Music Downloading Website (HTML,CSS,PHP Presentation)
Music Downloading Website (HTML,CSS,PHP Presentation)
 
Php create and invoke function
Php create and invoke functionPhp create and invoke function
Php create and invoke function
 
php
phpphp
php
 
File handling
File handlingFile handling
File handling
 
Php File Upload
Php File UploadPhp File Upload
Php File Upload
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 

Similaire à Php File Operations

Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Web Development Course: PHP lecture 3
Web Development Course: PHP lecture 3Gheyath M. Othman
 
PHP File Handling
PHP File Handling PHP File Handling
PHP File Handling Degu8
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHPMudasir Syed
 
File management
File managementFile management
File managementsumathiv9
 
File handing in C
File handing in CFile handing in C
File handing in Cshrishcg
 
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 handlingRai University
 
9780538745840 ppt ch05
9780538745840 ppt ch059780538745840 ppt ch05
9780538745840 ppt ch05Terry Yoast
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15Vishal Dutt
 
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.pptxAssadLeo1
 
file management in c language
file management in c languagefile management in c language
file management in c languagechintan makwana
 

Similaire à Php File Operations (20)

PHP Filing
PHP Filing PHP Filing
PHP Filing
 
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 Handling
PHP File Handling PHP File Handling
PHP File Handling
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHP
 
Files in php
Files in phpFiles in php
Files in php
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
File management
File managementFile management
File management
 
File handing in C
File handing in CFile handing in C
File handing in C
 
Php files
Php filesPhp files
Php files
 
PHP file handling
PHP file handling PHP file handling
PHP 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
pointer, structure ,union and intro to file handling
 
9780538745840 ppt ch05
9780538745840 ppt ch059780538745840 ppt ch05
9780538745840 ppt ch05
 
File io
File ioFile io
File io
 
Python files / directories part15
Python files / directories  part15Python files / directories  part15
Python files / directories part15
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
File operations
File operationsFile operations
File operations
 
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 management in c language
file management in c languagefile management in c language
file management in c language
 

Plus de Jamshid Hashimi

Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Jamshid Hashimi
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Jamshid Hashimi
 
Introduction to C# - Week 0
Introduction to C# - Week 0Introduction to C# - Week 0
Introduction to C# - Week 0Jamshid Hashimi
 
RIST - Research Institute for Science and Technology
RIST - Research Institute for Science and TechnologyRIST - Research Institute for Science and Technology
RIST - Research Institute for Science and TechnologyJamshid Hashimi
 
How Coding Can Make Your Life Better
How Coding Can Make Your Life BetterHow Coding Can Make Your Life Better
How Coding Can Make Your Life BetterJamshid Hashimi
 
Tips for Writing Better Code
Tips for Writing Better CodeTips for Writing Better Code
Tips for Writing Better CodeJamshid Hashimi
 
Launch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media IntegrationLaunch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media IntegrationJamshid Hashimi
 
Introduction to Blogging
Introduction to BloggingIntroduction to Blogging
Introduction to BloggingJamshid Hashimi
 
Introduction to Wordpress
Introduction to WordpressIntroduction to Wordpress
Introduction to WordpressJamshid Hashimi
 
CodeIgniter Helper Functions
CodeIgniter Helper FunctionsCodeIgniter Helper Functions
CodeIgniter Helper FunctionsJamshid Hashimi
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class ReferenceJamshid Hashimi
 
Managing Applications in CodeIgniter
Managing Applications in CodeIgniterManaging Applications in CodeIgniter
Managing Applications in CodeIgniterJamshid Hashimi
 
PHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniterPHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniterJamshid Hashimi
 

Plus de Jamshid Hashimi (20)

Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1
 
Introduction to C# - Week 0
Introduction to C# - Week 0Introduction to C# - Week 0
Introduction to C# - Week 0
 
RIST - Research Institute for Science and Technology
RIST - Research Institute for Science and TechnologyRIST - Research Institute for Science and Technology
RIST - Research Institute for Science and Technology
 
How Coding Can Make Your Life Better
How Coding Can Make Your Life BetterHow Coding Can Make Your Life Better
How Coding Can Make Your Life Better
 
Mobile Vision
Mobile VisionMobile Vision
Mobile Vision
 
Tips for Writing Better Code
Tips for Writing Better CodeTips for Writing Better Code
Tips for Writing Better Code
 
Launch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media IntegrationLaunch Your Local Blog & Social Media Integration
Launch Your Local Blog & Social Media Integration
 
Customizing Your Blog 2
Customizing Your Blog 2Customizing Your Blog 2
Customizing Your Blog 2
 
Customizing Your Blog 1
Customizing Your Blog 1Customizing Your Blog 1
Customizing Your Blog 1
 
Introduction to Blogging
Introduction to BloggingIntroduction to Blogging
Introduction to Blogging
 
Introduction to Wordpress
Introduction to WordpressIntroduction to Wordpress
Introduction to Wordpress
 
CodeIgniter Helper Functions
CodeIgniter Helper FunctionsCodeIgniter Helper Functions
CodeIgniter Helper Functions
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
 
Managing Applications in CodeIgniter
Managing Applications in CodeIgniterManaging Applications in CodeIgniter
Managing Applications in CodeIgniter
 
CodeIgniter Practice
CodeIgniter PracticeCodeIgniter Practice
CodeIgniter Practice
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 
PHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniterPHP Frameworks & Introduction to CodeIgniter
PHP Frameworks & Introduction to CodeIgniter
 
Exception & Database
Exception & DatabaseException & Database
Exception & Database
 
MySQL Record Operations
MySQL Record OperationsMySQL Record Operations
MySQL Record Operations
 

Dernier

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Dernier (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Php File Operations

  • 1. PHP File Operations Jamshid Hashimi Trainer, Cresco Solution http://www.jamshidhashimi.com jamshid@netlinks.af @jamshidhashimi ajamshidhashimi Afghanistan Workforce Development Program
  • 2. Agenda • Introduction • Creating a File • Opening a File – fopen() • Reading From a File – fgets() • Writing to File – fwrite() • Removing File – unlink() • Appending Data • File Locking – flock()
  • 3. Agenda • Uploading Files via an HTML Form • Getting File Information • More File Functions • Directory Functions • Getting a Directory Listing
  • 4. Introduction • Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files. • This is one of the most fundamental subjects of server side programming in general. Files are used in web applications of all sizes.
  • 5. Creating a File • In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending. $ourFileName = "testFile.txt"; $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); fclose($ourFileHandle);
  • 7. Opening a File • The fopen() function is used to open files in PHP. <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); fclose($file);
  • 8. Reading From a File • The fgets() function is used to read a single line from a file. <?php $file = fopen("welcome.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br>"; } fclose($file);
  • 9. Writing to a File • We can use php to write to a text file. The fwrite function allows data to be written to any type of file. $myFile = "testFile.txt"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "Kabul is the capitaln"; fwrite($fh, $stringData); $stringData = "Samangan is a provincen"; fwrite($fh, $stringData); fclose($fh);
  • 10. Removing File • In PHP you delete files by calling the unlink function. $myFile = "testFile.txt"; unlink($myFile);
  • 11. Appending Data $myFile = "testFile.txt"; $fh = fopen($myFile, 'a') or die("can't open file"); $stringData = "New Stuff 1n"; fwrite($fh, $stringData); $stringData = "New Stuff 2n"; fwrite($fh, $stringData); fclose($fh);
  • 12. File Locking • The key problem with file system operations is the situation you are in if two scripts attempt to write to a file at the same time. • The fopen() function, when called on a file, does not stop that same file from being opened by another script.
  • 13. File Locking • LOCK_SH to acquire a shared lock (reader). • LOCK_EX to acquire an exclusive lock (writer). • LOCK_UN to release a lock (shared or exclusive). $fp = fopen( $filename,"w"); // open it for WRITING ("w") if (flock($fp, LOCK_EX)) { // do your file writes here flock($fp, LOCK_UN); // unlock the file } else { // flock() returned false, no lock obtained print "Could not lock $filename!n"; }
  • 14. Uploading Files via an HTML Form • With PHP, it is possible to upload files to the server. <!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file"><br> <input type="submit" name="submit" value="Submit"> </form> </body> </html>
  • 15. Uploading Files via an HTML Form <?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br>"; echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; }
  • 16. Uploading Files via an HTML Form ; Maximum allowed size for uploaded files. upload_max_filesize = 40M ; Must be greater than or equal to upload_max_filesize post_max_size = 40M
  • 17. Directory Functions • scandir() • getcwd() <?php print_r(scandir(”projects")); ?> <?php echo getcwd(); ?>
  • 18. Directory Functions • chdir() – The chdir() function changes the current directory to the specified directory. <?php //Get current directory echo getcwd(); echo "<br />"; //Change to the images directory chdir(”projects"); echo "<br />"; echo getcwd();
  • 19. DEMO

Notes de l'éditeur

  1. fgets(file,length):file: Required. Specifies the file to read fromLength:Optional. Specifies the number of bytes to read. Default is 1024 bytes.
  2. The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort.