I use this php code to retrieve the files stored in a directory .
if ($handle = opendir('FolderPath')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n <br />" ;
}
}
closedir($handle);
}
This Directory only holds PHP files , how would i be able to remove the extension from the echoed results? example: ( index.php would become index )
The easiest way to do this is by using the glob function:
foreach (glob('path/to/files/*.php') as $fileName) {
//extension .php is guaranteed here
echo substr($fileName, 0, -4), PHP_EOL;
}
The advantages of glob here is that you can do away with those pesky readdir and opendir calls. The only slight "disatvantage" is that the value of $fileName will contain the path, too. However, that's an easy fix (just add one line):
foreach (glob('path/to/files/*.php') as $fullName) {
$fileName = explode('/', $fullName);
echo substr(
end($fileName),//the last value in the array is the file name
0, -4),
PHP_EOL;
}
This should work for you:
echo basename($entry, ".php") . "\n <br />" ;
A quick way to do this is
<?php
if ($handle = opendir('FolderPath')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
echo $file_name;
}
}
closedir($handle);
?>
$files = glob('path/to/files/*.*');
foreach($files as $file) {
if (! is_dir($file)) {
$file = pathinfo($file);
echo "<br/>".$file['filename'];
}
}
Use pathinfo()
$entry = substr($entry, 0, strlen($entry) - 4);
Note that this is a simple and quick solution which works perfect if you are 100% sure that your extension is in the form of *.xxx. However if you need a more flexible and safer solution regarding possible different extension lenghts, than this solution is not recommended.
Elegant solution would be to use $suffix attribute of DirectoryIterator::getBasename() method. When provided, $suffix will be removed on each call. For known extension, you can use:
foreach (new DirectoryIterator('/full/dir/path') as $file) {
if ($file->isFile()) {
print $file->getBasename('.php') . "\n";
}
}
or this, as an universal solution:
foreach (new DirectoryIterator('/full/dir/path') as $file) {
if ($file->isFile()) {
print $file->getBasename($file->getExtension() ? '.' . $file->getExtension() : null) . "\n";
}
}
PHP docs: http://php.net/manual/en/directoryiterator.getbasename.php
Related
I checked at php.net opendir() but found no way to control the order of the files that opendir() gets.
I have a slideshow and I have problems controling the order of the images. I tried changing names and use 01.img,02.img,...,20.img but no sucess.
My script:
<?php
$path2 = "./img/";
function createDir($path2 = './img'){
if ($handle = opendir($path2)){
echo "<ul class=\"ad-thumb-list\">";
while (false !== ($file = readdir($handle))){
if (is_dir($path2.$file) && $file != '.' && $file !='..')
printSubDir($file, $path2, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path2);
echo "</ul>";
}
}
function printQueue($queue, $path2){
foreach ($queue as $file){
printFile($file, $path2);
}
}
function printFile($file, $path2){
if ($file=="thumbs.db") {echo "";}
else{
echo "<li><a href=\"".$path2.$file."\">";
echo "<img src=\"".$path2.$file."\" class='thumbnail'></a></li>";
}
}
/*function printSubDir($dir, $path2)
{
}*/
createDir($path2);
?>
Use scandir() and natsort().
Rewritten code:
function createDir($path2 = './img'){
$dirContents = scandir($path2);
natsort($dirContents);
echo "<ul class=\"ad-thumb-list\">";
// You should actually add the line below!
// $queue = array();
foreach ($dirContents as $entry) {
if ($entry == '.' || $entry == '..') {
continue;
}
$entryPath = $path2 . $entry;
if (is_dir($entryPath)) {
printSubDir($entry, $path2, $queue);
}
else {
$queue[] = $entry;
}
}
printQueue($queue, $path2);
echo "</ul>";
}
}
If you are using PHP 5, you could try using scandir() instead. It has an argument for sorting.
http://us1.php.net/scandir
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
As #Steven has already said, you may not be able to change the output of opendir(), but there's nothing stopping you from sorting the array afterwards.
To do this, have a look at the natsort() function, which is designed to properly sort strings like those you're using for file names.
hi I'm writing a script to loop through the current directory and list all sub directories
all is working fine but i can't get it to exclude folders starting with an _
<?php
$dir = __dir__;
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
echo("<ul>");
while (($file = readdir($dh)) !== false) {
if ($file == '.' || $file == '..' || $file == '^[_]*$' ) continue;
if (is_dir($file)) {
echo "<li> <a href='$file'>$file</a></li>";
}
}
closedir($dh);
}
}
?>
you can use substr[docs] like :
|| substr($file, 0, 1) === '_'
No need for a regex, use $file[0] == '_' or substr($file, 0, 1) == '_'
If you do want a regex, you need to use preg_match() to check: preg_match('/^_/', $file)
Or, if you would like to use regexp, you should use regex functions, like preg_match: preg_match('/^_/', $file); but as said by ThiefMaster, in this case a $file[0] == '_' suffices.
A more elegant solution is to use SPL. The GlobIterator can help you out. Each item is an instance of SplFileInfo.
<?php
$dir = __DIR__ . '/[^_]*';
$iterator = new GlobIterator($dir, FilesystemIterator::SKIP_DOTS);
if (0 < $iterator->count()) {
echo "<ul>\n";
foreach ($iterator as $item) {
if ($item->isDir()) {
echo sprintf("<li>%s</li>\n", $item);
}
}
echo "</ul>\n";
}
i want to write a page that will traverse a specified directory.... and get all the files in that directory...
in my case the directory will only contain images and display the images with their links...
something like this
How to Do it
p.s. the directory will not be user input.. it will be same directory always...
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
use readdir
<?php
//define directory
$dir = "images/";
//open directory
if ($opendir = opendir($dir)){
//read directory
while(($file = readdir($opendir))!= FALSE ){
if($file!="." && $file!= ".."){
echo "<img src='$dir/$file' width='80' height='90'><br />";
}
}
}
?>
source: phpacademy.org
You'll want to use the scandir function to walk the list of files in the directory.
Hi you can use DirectoryIterator
try {
$dir = './';
/* #var $Item DirectoryIterator */
foreach (new DirectoryIterator($dir) as $Item) {
if($Item->isFile()) {
echo $Item->getFilename() . "\n";
}
}
} catch (Exception $e) {
echo 'No files Found!<br />';
}
If you want to pass directories recursively:
http://php.net/manual/en/class.recursivedirectoryiterator.php
/**
* function get files
* #param $path string = path to fine files in
* #param $accept array = array of extensions to accept
* #param currentLevel = 0, stopLevel = 0
* #return array of madmanFile objects, but you can modify it to
* return whatever suits your needs.
*/
public static function getFiles( $path = '.', $accept, $currentLevel = 0, $stopLevel = 0){
$path = trim($path); //trim whitespcae if any
if(substr($path,-1)=='/'){$path = substr($path,0,-1);} //cutoff the last "/" on path if provided
$selectedFiles = array();
try{
//ignore these files/folders
$ignoreRegexp = "/\.(T|t)rash/";
$ignore = array( 'cgi-bin', '.', '..', '.svn');
$dh = #opendir( $path );
//Loop through the directory
while( false !== ( $file = readdir( $dh ) ) ){
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) and !preg_match($ignoreRegexp,$file)){
$spaces = str_repeat( ' ', ( $currentLevel * 4 ) );
// Its a directory, so we need to keep reading down...
if( is_dir( "$path/$file" ) ){
//merge current selectFiles array with recursion return which is
//another array of selectedFiles
$selectedFiles = array_merge($selectedFiles,MadmanFileManager::getFiles( "$path/$file", $accept, ($currentLe$
} else{
$info = pathinfo($file);
if(in_array($info['extension'], $accept)){
$selectedFiles[] = new MadmanFile($info['filename'], $info['extension'], MadmanFileManager::getSize($
}//end if in array
}//end if/else is_dir
}
}//end while
closedir( $dh );
// Close the directory handle
}catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return $selectedFiles;
}
You could as others have suggested check every file in the dir, or you could use glob to identify files based on extension.
I use something along the lines of:
if ($dir = dir('images'))
{
while(false !== ($file = $dir->read()))
{
if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
{
// do stuff with the images
}
}
}
else { echo "Could not open directory"; }
You could also try the glob function:
$path = '/your/path/';
$pattern = '*.{gif,jpg,jpeg,png}';
$images = glob($path . $pattern, GLOB_BRACE);
print_r($images);
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
For further reference :http://php.net/manual/en/function.opendir.php
I would start off by creating a recursive function:
function recurseDir ($dir) {
// open the provided directory
if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].$dir)) {
// we dont want the directory we are in or the parent directory
if ($entry !== "." && $entry !== "..") {
// recursively call the function, if we find a directory
if (is_dir($_SERVER['DOCUMENT_ROOT'].$dir.$entry)) {
recurseDir($dir.$entry);
}
else {
// else we dont find a directory, in which case we have a file
// now we can output anything we want here for each file
// in your case we want to output all the images with the path under it
echo "<img src='".$dir.$entry."'>";
echo "<div><a href='".$dir.$entry."'>".$dir.$entry."</a></div>";
}
}
}
}
The $dir param needs to be in the following format:
"/path/" or "/path/to/files/"
Basically, just don't include the server root, because i have already done that below using $_SERVER['DOCUMENT_ROOT'].
So, in the end just call the recurseDir function we just made in your code once, and it will traverse any sub folders and output the image with the link under it.
I am looping through a list of files in a directory and I want to match a substring that I have with the filename. If the filename contains the substring then return that file name so that I can delete it. I have done the following and its just returning everything:
while ($file = readdir($dir_handle)) {
$extension = strtolower(substr(strrchr($file, '.'), 1));
if($extension == "sql" || $extension == "txt" ) {
$pos = strpos($file, $session_data['user_id']);
if($pos === true) {
//unlink($file);
echo "$file<br />";
}else {
// string not found
}
}
}
What am I doing wrong?
Thanks all for any help
strpos returns an integer or FALSE. You'll want to update your test to be
$pos !== FALSE
Then - if you want to delete the file you can uncomment the unlink() call. I'm not sure what you mean by "return so I can delete".
Assuming you are on Linux you can do this using the [glob()][1] function with the GLOB_BRACE option:
$files = glob('*.{sql,txt}', GLOB_BRACE);
You might also mix in the user_id there.
Not sure if it works on Windows. See http://de.php.net/glob and mind the note about the GLOB_BRACE option.
if ($handle = opendir('/path/to/dir/') {
$extensions = array('sql' => 1, 'txt' => 1);
while (false !== ($file = readdir($handle))) {
$ext = strtolower(substr(strrchr($file, '.'), 1));
if (isset($extensions[$ext]) && strpos($file, $session_data['user_id']) !== false)
echo "$file<br />";
else
echo "no match<br />";
}
}
}
you can use SPL to do it recursively
foreach (new DirectoryIterator('/path') as $file) {
if($file->isDot()) continue;
$filename = $file->getFilename();
$pathname = $file->getPathname();
if ( strpos ($filename ,".sql") !==FALSE ) {
echo "Found $pathname\n";
$pos = strpos($filename, $session_data['user_id']);
......
#unlink($pathname); #remove your file
}
}
Hay all im using a simple look to get file names from a dir
if ($handle = opendir('news_items/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
}
}
}
the files are being outputted news last, oldest first.
How can i reverse this so the newest files are first?
Get the file list into an array, then array_reverse() it :)
the simplest option is to invoke a shell command
$files = explode("\n", `ls -1t`);
if, for some reason, this doesn't work, try glob() + sort()
$files = glob("*");
usort($files, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));
Pushing every files in an array whit mtime as key allow you to reverse sort that array:
<?php
$files = array();
if ($handle = opendir('news_items/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$mtime = filemtime('news_items/' . $file);
if (!is_array($files[$mtime])) {
$files[$mtime] = array();
}
array_push($files[$mtime], $file);
}
}
}
krsort($files);
foreach ($files as $mt=>$fi) {
sort($fi);
echo date ("F d Y H:i:s.", $mt) . " : " . implode($fi, ', ') . "\n";
}
?>