Unit-III
Working with Files and
Directories in PHP
Understanding Files and Directories
In PHP, working with files and directories involves interacting
with the file system. You can create, open, read, write, rename,
and delete files or directories.
Opening and Closing a File
Opening a file: PHP provides the fopen() function to open a file. You can
open a file in various modes:
• 'r': Read-only, starts at the beginning of the file.
• 'w': Write-only, truncates the file to zero length or creates a new file if
it doesn't exist.
• 'a': Write-only, appends to the end of the file
Example:
Opening a file: Use the fopen() function
$file = fopen("example.txt", "r");
// Opens the file in read-only mode
Closing a file: Use the fclose() function to close an opened file.
fclose($file);
// Closes the file
Copying, Renaming, and Deleting a File
• Copying a file: You can use the copy() function to copy files.
copy("source.txt", "destination.txt");
• Renaming a file: The rename() function allows you to rename a file or
move it to a different directory.
rename("oldname.txt", "newname.txt");
• Deleting a file: To delete a file, use the unlink() function.
unlink("example.txt")
Working with Directories
Creating a directory: Use the mkdir() function to create a new
directory.
mkdir("new_directory");
<?php
$dirPath = "uploads/";
if (!file_exists($dirPath))
{
mkdir($dirPath, 0777, true);
echo "Directory created successfully.";
}
else
{
echo "Directory already exists.";
}
?>
Explanation of the Script
• $dirPath = "uploads/";:
You are defining the path for the directory to be created, in this case,
uploads/.
• file_exists($dirPath):
This checks if the directory already exists at the specified path.
• mkdir($dirPath, 0777, true):
If the directory does not exist, this function creates it.
0777 specifies the permissions (read, write, and execute permissions
for everyone).
The third parameter true allows creating nested directories if needed.
Read a Directory
<?php
$dirPath = “a/b/c”;
if ($handle = opendir($dirPath))
{
while (false !== ($entry = readdir($handle)))
{
if ($entry != "." && $entry != "..")
{
echo "$entry<br>";
}
}
closedir($handle);
}
else
{
echo "Unable to open directory.";
}
?>
Explanation of the Script
• $dirPath = "uploads/";:
Specifies the path of the directory to be opened.
• opendir($dirPath):
Opens the directory for reading. The directory handle is stored in the
variable $handle.
• readdir($handle):
Reads each entry in the directory. It returns false when all the entries have
been read.
In the loop, it reads each file or folder one by one.
• if ($entry != "." && $entry != ".."):
Skips the special entries . and .. (representing the current and parent
directories).
• echo "$entry<br>";:
Outputs each file or folder name followed by an HTML line break
(<br>).
• closedir($handle):
Closes the directory handle once reading is complete.
File Uploading & Downloading
File Uploading: To allow file uploads, your HTML form should contain the
attribute enctype="multipart/form-data".
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
File Uploading
In upload.php, handle the uploaded file using PHP’s $_FILES
array.
if(isset($_FILES['file’]))
{
$filename = $_FILES['file']['name'];
$tempname = $_FILES['file']['tmp_name'];
move_uploaded_file($tempname, "uploads/" . $filename);
}
File Downloading
File Downloading: You can force a file download by sending
appropriate headers.
$file = "path/to/file.txt";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($file).'"');
readfile($file);
Generating Images with PHP
Basics of Computer Graphics in PHP: PHP can dynamically
generate images using the GD library, which is built-in in most
PHP installations. You can create images from scratch,
manipulate existing ones, and output them in various formats
like PNG, JPEG, and GIF.
Creating an Image
Step 1: Create a blank image using imagecreate() or
imagecreatetruecolor() for a higher-quality image.
$width = 200;
$height = 100;
$image = imagecreatetruecolor($width, $height);
Step 2: Allocate colors with imagecolorallocate().
$background = imagecolorallocate($image, 0, 0, 0); // Black background
$text_color = imagecolorallocate($image, 255, 255, 255); // White text
Step 3: Add shapes or text using functions like imageline(),
imagefilledrectangle(), or imagestring().
imagestring($image, 5, 10, 10, "Hello World!", $text_color); //
Adds text
Step 4: Output the image in a desired format (e.g., PNG).
header('Content-Type: image/png');
imagepng($image);
Step 5: Free up memory with imagedestroy().
imagedestroy($image);
<?php
$width = 200; // Create a blank image
$height = 100;
$image = imagecreatetruecolor($width, $height);
// Allocate colors
$background = imagecolorallocate($image, 0, 0, 255); // Blue background
$text_color = imagecolorallocate($image, 255, 255, 255); // White text
imagefill($image, 0, 0, $background); // Fill the background
imagestring($image, 5, 50, 40, "Hello, PHP!", $text_color); // Add text to the image
header('Content-Type: image/png'); // Set the header for PNG output
imagepng($image); // Output the image
imagedestroy($image); // Free memory
?>

More Related Content

PPTX
PHP File Handling
PPT
Files and Directories in PHP
PDF
File system
PDF
Web Development Course: PHP lecture 3
PPSX
DIWE - File handling with PHP
PPT
9780538745840 ppt ch05
PPT
PHP - Introduction to File Handling with PHP
PPT
Filing system in PHP
PHP File Handling
Files and Directories in PHP
File system
Web Development Course: PHP lecture 3
DIWE - File handling with PHP
9780538745840 ppt ch05
PHP - Introduction to File Handling with PHP
Filing system in PHP

Similar to Unit3IIpartpptx__2024_10_17_19_07_58 2.pptx (20)

PPTX
PHP Filing
PPTX
4-chapter-File & Directores.pptx debre CTABOUR UNIversit
PPTX
Php File Operations
PPTX
object oriented programming in PHP & Functions
PPTX
File Handling
PPTX
File Handling
PPT
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
PPTX
File handle in PROGRAMMable extensible interpreted .pptx
PPT
Php i basic chapter 4
PPTX
On secure application of PHP wrappers
DOCX
Php files
PPTX
File Handling in C
PPT
John's Top PECL Picks
PPTX
Ch3(working with file)
PPT
Php File Operations
PPTX
Filesin c++
PPT
eZ Publish Cluster Unleashed
PPTX
File handling in Python
PPTX
File management
PPTX
File handling With Solve Programs
PHP Filing
4-chapter-File & Directores.pptx debre CTABOUR UNIversit
Php File Operations
object oriented programming in PHP & Functions
File Handling
File Handling
BITS: Introduction to Linux - Text manipulation tools for bioinformatics
File handle in PROGRAMMable extensible interpreted .pptx
Php i basic chapter 4
On secure application of PHP wrappers
Php files
File Handling in C
John's Top PECL Picks
Ch3(working with file)
Php File Operations
Filesin c++
eZ Publish Cluster Unleashed
File handling in Python
File management
File handling With Solve Programs
Ad

Recently uploaded (20)

PDF
The Impact of Policy Changes on Legal Communication Strategies (www.kiu.ac.ug)
PPTX
OS ALL UNITS MATxtdtc5ctc5cycgctERIAL.pptx
PDF
The Role of School Boards in Educational Management (www.kiu.ac.ug)
PDF
The Evolution of Legal Communication through History (www.kiu.ac.ug)
PDF
BeMetals_Presentation_September_2025.pdf
PDF
Shriram Finance, one of India's leading financial services companies, which o...
PDF
Implementing Steam Education: Challenges and Solutions (www.kiu.ac.ug)
PPTX
Warehouse. B pptx
PPTX
Biomass_Energy_PPT_FIN AL________________.pptx
PDF
France's Top 5 Promising EdTech Companies to Watch in 2025.pdf
PDF
The Impact of Historical Events on Legal Communication Styles (www.kiu.ac.ug)
DOCX
“Strategic management process of a selected organization”.Nestle-docx.docx
PPTX
UNIT 3 INTERNATIONAL BUSINESS [Autosaved].pptx
PDF
The Dynamic CLOs Shaping the Future of the Legal Industry in 2025.pdf
PPTX
TS - CIM-as of august 2023 .pptx
PDF
109422672-Doc-8973-05-Security-Manual-Seventh-Edition.pdf
PDF
How to run a consulting project from scratch
PPTX
Enterprises are Classified into Two Categories
PPTX
Accounting Management SystemBatch-4.pptx
PDF
Integrating Porter-Lawler Theory of Motivation and Hofstede's Dimensions of N...
The Impact of Policy Changes on Legal Communication Strategies (www.kiu.ac.ug)
OS ALL UNITS MATxtdtc5ctc5cycgctERIAL.pptx
The Role of School Boards in Educational Management (www.kiu.ac.ug)
The Evolution of Legal Communication through History (www.kiu.ac.ug)
BeMetals_Presentation_September_2025.pdf
Shriram Finance, one of India's leading financial services companies, which o...
Implementing Steam Education: Challenges and Solutions (www.kiu.ac.ug)
Warehouse. B pptx
Biomass_Energy_PPT_FIN AL________________.pptx
France's Top 5 Promising EdTech Companies to Watch in 2025.pdf
The Impact of Historical Events on Legal Communication Styles (www.kiu.ac.ug)
“Strategic management process of a selected organization”.Nestle-docx.docx
UNIT 3 INTERNATIONAL BUSINESS [Autosaved].pptx
The Dynamic CLOs Shaping the Future of the Legal Industry in 2025.pdf
TS - CIM-as of august 2023 .pptx
109422672-Doc-8973-05-Security-Manual-Seventh-Edition.pdf
How to run a consulting project from scratch
Enterprises are Classified into Two Categories
Accounting Management SystemBatch-4.pptx
Integrating Porter-Lawler Theory of Motivation and Hofstede's Dimensions of N...
Ad

Unit3IIpartpptx__2024_10_17_19_07_58 2.pptx

  • 1. Unit-III Working with Files and Directories in PHP
  • 2. Understanding Files and Directories In PHP, working with files and directories involves interacting with the file system. You can create, open, read, write, rename, and delete files or directories.
  • 3. Opening and Closing a File Opening a file: PHP provides the fopen() function to open a file. You can open a file in various modes: • 'r': Read-only, starts at the beginning of the file. • 'w': Write-only, truncates the file to zero length or creates a new file if it doesn't exist. • 'a': Write-only, appends to the end of the file
  • 4. Example: Opening a file: Use the fopen() function $file = fopen("example.txt", "r"); // Opens the file in read-only mode Closing a file: Use the fclose() function to close an opened file. fclose($file); // Closes the file
  • 5. Copying, Renaming, and Deleting a File • Copying a file: You can use the copy() function to copy files. copy("source.txt", "destination.txt"); • Renaming a file: The rename() function allows you to rename a file or move it to a different directory. rename("oldname.txt", "newname.txt"); • Deleting a file: To delete a file, use the unlink() function. unlink("example.txt")
  • 6. Working with Directories Creating a directory: Use the mkdir() function to create a new directory. mkdir("new_directory");
  • 7. <?php $dirPath = "uploads/"; if (!file_exists($dirPath)) { mkdir($dirPath, 0777, true); echo "Directory created successfully."; } else { echo "Directory already exists."; } ?>
  • 8. Explanation of the Script • $dirPath = "uploads/";: You are defining the path for the directory to be created, in this case, uploads/. • file_exists($dirPath): This checks if the directory already exists at the specified path.
  • 9. • mkdir($dirPath, 0777, true): If the directory does not exist, this function creates it. 0777 specifies the permissions (read, write, and execute permissions for everyone). The third parameter true allows creating nested directories if needed.
  • 11. <?php $dirPath = “a/b/c”; if ($handle = opendir($dirPath)) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { echo "$entry<br>"; } } closedir($handle); } else { echo "Unable to open directory."; } ?>
  • 12. Explanation of the Script • $dirPath = "uploads/";: Specifies the path of the directory to be opened. • opendir($dirPath): Opens the directory for reading. The directory handle is stored in the variable $handle. • readdir($handle): Reads each entry in the directory. It returns false when all the entries have been read. In the loop, it reads each file or folder one by one.
  • 13. • if ($entry != "." && $entry != ".."): Skips the special entries . and .. (representing the current and parent directories). • echo "$entry<br>";: Outputs each file or folder name followed by an HTML line break (<br>). • closedir($handle): Closes the directory handle once reading is complete.
  • 14. File Uploading & Downloading File Uploading: To allow file uploads, your HTML form should contain the attribute enctype="multipart/form-data". <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form>
  • 15. File Uploading In upload.php, handle the uploaded file using PHP’s $_FILES array. if(isset($_FILES['file’])) { $filename = $_FILES['file']['name']; $tempname = $_FILES['file']['tmp_name']; move_uploaded_file($tempname, "uploads/" . $filename); }
  • 16. File Downloading File Downloading: You can force a file download by sending appropriate headers. $file = "path/to/file.txt"; header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'"'); readfile($file);
  • 17. Generating Images with PHP Basics of Computer Graphics in PHP: PHP can dynamically generate images using the GD library, which is built-in in most PHP installations. You can create images from scratch, manipulate existing ones, and output them in various formats like PNG, JPEG, and GIF.
  • 18. Creating an Image Step 1: Create a blank image using imagecreate() or imagecreatetruecolor() for a higher-quality image. $width = 200; $height = 100; $image = imagecreatetruecolor($width, $height); Step 2: Allocate colors with imagecolorallocate(). $background = imagecolorallocate($image, 0, 0, 0); // Black background $text_color = imagecolorallocate($image, 255, 255, 255); // White text
  • 19. Step 3: Add shapes or text using functions like imageline(), imagefilledrectangle(), or imagestring(). imagestring($image, 5, 10, 10, "Hello World!", $text_color); // Adds text Step 4: Output the image in a desired format (e.g., PNG). header('Content-Type: image/png'); imagepng($image); Step 5: Free up memory with imagedestroy(). imagedestroy($image);
  • 20. <?php $width = 200; // Create a blank image $height = 100; $image = imagecreatetruecolor($width, $height); // Allocate colors $background = imagecolorallocate($image, 0, 0, 255); // Blue background $text_color = imagecolorallocate($image, 255, 255, 255); // White text imagefill($image, 0, 0, $background); // Fill the background imagestring($image, 5, 50, 40, "Hello, PHP!", $text_color); // Add text to the image header('Content-Type: image/png'); // Set the header for PNG output imagepng($image); // Output the image imagedestroy($image); // Free memory ?>