Working With Directories in PHP

[ad_1]

Working With Directories in PHP includes making a listing, altering directories, itemizing the content material of a listing, and in addition deleting a listing.

PHP gives a number of in-built capabilities that allow us to carry out operations on directories. The next part discusses a few of these capabilities.

Features for Working With Directories in PHP

To start with, we create a listing. For this objective, there’s a perform with the title mkdir. The next examples present learn how to create a single listing, in addition to nested directories. These examples are executed on a Home windows system.

Making a Listing

The mkdir() perform takes the trail of the listing to be created because the necessary parameter. Due to this fact, the next instance creates a listing with the title dir1 within the present listing.

<?php
   $path="dir1/";
   mkdir($path);
?>

Creating Listing Recursively

The next instance exhibits learn how to create nested directories. Right here, we have to specify the worth true for the third parameter referred to as ‘recursive’. So, we additionally have to specify the mode because the second parameter. Nevertheless, in a Home windows system, this parameter is ignored. On account of the execution of the next code, these three directories – d1, d2, and d3 might be created.

<?php
   $path="d1/d2/d3";
   mkdir($path, 0777, true);
?>

Altering Listing

For the aim of adjusting the listing, PHP gives a perform chdir(). Additionally, the perform getcwd() returns the title of the present working listing. The next code exhibits the present working listing earlier than and after the decision to the chdir() perform.

<?php
   //show present working listing
   echo 'Present Working Listing...<br>';
   echo getcwd();
   chdir("d1");
   echo '<br>Modified to: <br>';
   echo getcwd();
?>
Working With Directories in PHP - Changing Directory
Working With Directories in PHP – Altering Listing

Itemizing the Contents of a Listing

Principally, the scandir() perform takes the trail as a parameter and returns an array of all of the information and directories inside the given path.

<?php
   $dir="../../Recordsdata";
   $arr=scandir($dir);
   print_r($arr);
?>

Output

Listing Directory in PHP
Itemizing Listing in PHP

Studying the Contents of a Listing with One Entry at a Time

Equally, the readdir() perform returns the content material of a listing. Nevertheless, it returns one entry at a time. Additionally, we have to name the opendir() perform to open the listing.

<?php
   $dir="../../Recordsdata";
   $d=opendir($dir);
   whereas($f=readdir($d))
   {
	echo "Filename: ",$f,"<br>";
    }
?>

Output

Example of readdir() in PHP
Instance of readdir() in PHP

Additional Studying

Examples of Array Features in PHP

Primary Applications in PHP

programmingempire

princites.com

[ad_2]

Source_link

Leave a Comment