hfarazm
hfarazm

Reputation: 1417

create multiple directories using loop in php

I am taking data from text file( data is: daa1 daa2 daa3 on separate lines) then trying to make folders with exact name but only daa3 folders is created. Also when i use integer it creates all folders, same is the case with static string i.e "faraz".

$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$line =0;
 while ( $line < 5 )
{
    $a = fgets($f, 100); 

    $nl = mb_strtolower($line);
    $nl = "checkmeck/".$nl;
    $nl =  $nl."faraz"; // it works for static value i.e for faraz
//$nl =  $nl.$a; // i want this to be the name of folder
    if (!file_exists($nl)) {
    mkdir($nl, 0777, true);


}
$line++;
}

kindly help

Upvotes: 0

Views: 1416

Answers (2)

Kodr.F
Kodr.F

Reputation: 14390

use feof function its much better to get file content also line by line

Check this full code

 $file         = __DIR__."/dataFile.txt";
$linecount    = 0;
$handle       = fopen($file, "r");
$mainFolder   = "checkmeck";

while(!feof($handle))
{
  $line       = fgets($handle);
  $foldername = $mainFolder."/".trim($line);

  //$line is line name daa1,daa2,daa3 etc
  if (!file_exists($foldername)) {
    mkdir($foldername, 0777, true);
  }
  $linecount++;
  unset($line);
}

fclose($handle);

output folders

1countfaraz
2countfaraz
3countfaraz

Upvotes: 3

Travesty3
Travesty3

Reputation: 14469

Not sure why you're having trouble with your code, but I find it to be more straightforward to use file_get_contents() instead of fopen() and fgets():

$file = __DIR__."/dataFile.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
    $nl = "checkmeck/". $line;
    if (!file_exists($nl)) {
        echo 'Creating file '. $nl . PHP_EOL;
        mkdir($nl, 0777, true);
        echo 'File '. $nl .' has been created'. PHP_EOL;
    } else {
        echo 'File '. $nl .' already exists'. PHP_EOL;
    }
}

The echo statements above are for debugging so that you can see what your code is doing. Once it is working correctly, you can remove them.

So you get the entire file contents, split it (explode()) by the newline character (\n), and then loop through the lines in the file. If what you said is true, and the file looks like:

daa1
daa2
daa3

...then it should create the following folders:

checkmeck/daa1
checkmeck/daa2
checkmeck/daa3

Upvotes: 1

Related Questions