Home > Enterprise >  how to properly print all the files name in a directory using php
how to properly print all the files name in a directory using php

Time:02-02

The code below successfully print an array result of all the php files in a folder.

$search_data = glob('download/*.php');
print_r($search_data);

Below is the Array Result

Array ( [0] => download/index.php
[1] => download/register.php ) 

Here is my question: Please How do I print all the files.

I have tried adding the code below but it throws error
Uncaught TypeError: json_decode(): Argument #1 ($json) must be of type string, array given

$json = json_decode($search_data, true);
foreach ($json as $data) {

//print or list all the files 
    echo  $files = $data;
  echo "<br>";
}

CodePudding user response:

If I understand you correctly, its as simple as...

<?php

$files = glob('download/*.php');

foreach($files as $file){
    echo $file . '<br />';
}

CodePudding user response:

$search_data isn't a json string to decode. It's already an array. You'd just loop through it normally. Then use echo "$data<br>\n";

Thus you'd have:

$search_data = glob('download/*.php');
foreach ($search_data as $data) {
    echo "$data<br>\n";
}

CodePudding user response:

basically you can cycle the $search_data array into a foreach loop. If you want to print only the name of each file, you can use pathinfo method to retrieve the base name.

Hope it’s help. Best Marco

  •  Tags:  
  • Related