SlideShare una empresa de Scribd logo
1 de 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?

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Php array
Php arrayPhp array
Php array
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Input output streams
Input output streamsInput output streams
Input output streams
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Php basics
Php basicsPhp basics
Php basics
 
PHP
PHPPHP
PHP
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET framework
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Operators in PHP
Operators in PHPOperators in PHP
Operators in PHP
 
file handling c++
file handling c++file handling c++
file handling c++
 
Assembler
AssemblerAssembler
Assembler
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 

Destacado

Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi Vipin sharma
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operationsmussawir20
 
Chapter 08 php advance
Chapter 08   php advanceChapter 08   php advance
Chapter 08 php advanceDhani Ahmad
 
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)Anil Kumar
 
Php create and invoke function
Php create and invoke functionPhp create and invoke function
Php create and invoke functionargusacademy
 
Php tutorial
Php tutorialPhp tutorial
Php tutorialNiit
 

Destacado (16)

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
 
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
 
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
 

Similar a 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
 

Similar a 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
 
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
 
File handling in C
File handling in CFile handling in C
File handling in C
 

Más 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
 

Más 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
 

Último

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
 
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
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 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
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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
 
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
 

Último (20)

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
 
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
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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...
 
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
 

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

Notas del editor

  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.