Mdlc
Mdlc

Reputation: 7288

Php get basename of files in directory

I would like to create a links to all files in a specific directory. Example

Directory: /account contains;

user/
data/
register.txt
login.txt
instructions.docx

I would like to have php generate:

<a href="action.php?action=register.txt">register</a>
<a href="action.php?action=login.txt">login</a>

Preferably only create link of the .txt files.

I have this code:

<?php
 if ($handle = opendir('account')) {
 while (false !== ($file = readdir($handle)))
 {
    if (($file != ".") 
     && ($file != ".."))
    {
        $test=`basename "$file"`; //this is line 8
        $thelist = '<a href="action.php?action='.$file.'">'.$test.'</a>';
    }
   }



   closedir($handle);
  } 
  ?>

 <P>List of files:</p>
 <UL>
 <P><?=$thelist?></p>
 </UL>

But it gives this error:

 Warning: shell_exec() has been disabled for security reasons in /public_html/directory/checkit.php on line 8 

And even if it would work it would display even files that do not have the .txt extension. (I know that the security reasons error can frequently be resolved by changing some php settings, or changing some permissions? But I know there is a way to do this without changing all my settings).

Upvotes: 0

Views: 1129

Answers (4)

uruk
uruk

Reputation: 1306

You could use scandir() to get the content of a folder:

$theList = '';
$content = scandir('account');
foreach($content as $aFileInIt) {
    // skip files that do not end on ".txt"
    if(!preg_match('/(\.txt)$/i', $aFileInIt))
         continue;
    // save a-elements to variable
    // UPDATE: take the file's basename as the linktext
    $theList .= '<li><a href="action.php?action='.$aFileInIt.'">'.str_ireplace('.txt', '', $aFileInIt).'</a></li>';
}

And later, in order to have a correct UL-element:

echo '<ul>'.$theList.'</ul>';

Upvotes: 1

Baba
Baba

Reputation: 95101

Use GlobIterator instead ...

$fs = new GlobIterator(__DIR__.'/*.txt');
foreach ($fs as $file) {
    printf("<a href=\"action.php?action=%s\">%s</a> <br />\n", 
           urlencode($file),
           $file->getBasename(".txt"));
}

Note there are a lot of security implications to passing the full file path to action=, I think it's a bad design and not a good idea.

Just pass the file name and a security token instead

Upvotes: 0

web-nomad
web-nomad

Reputation: 6003

Use glob function.

$directory = 'PATH_TO_YOUR_DIRECTORY' . DIRECTORY_SEPARATOR;

foreach( glob( $directory . "*.txt" ) as $filename ) {
  if( ! is_dir( $filename ) ) {
    echo basename( $filename ) . "\n";
  }
}

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Replace the line

$test=`basename "$file"`; //this is line 8

by

$test=basename("$file");

Read Docs basename()

Upvotes: 4

Related Questions