Well, the title is probably not very helpful. I'm not sure how to describe this error. I'm sure it's caused by something stupid on my part. For the life of me though, I can't figure it out.
Here's what I'm trying to do: There's a list of folders in my directory "img/gallery"
Within each of those folders are images
There's also a folder called "img/thumbs" which is structured exactly the same but with thumbnail images
I am writing a script that does two things: it displays the names of the folders within "img/gallery" and displays a list of thumbnails with links to the images in that folder.
These two components, when run separately, work fine. Put together, I get an error at
if ($handle = opendir('img/gallery/$file/'))
saying that $file is not a valid directory.
Here's the code:
`
if ($handle = opendir('img/gallery/')) {
$blacklist = array('.', '..', 'somedir', 'somefile.php');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "<h2>$file</h2>\n";
}
}
closedir($handle);
}
echo "<P class='gallery'>\n";
if ($handle = opendir('img/gallery/$file/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a class='fancybox' href='img/gallery/$file/$entry' data-fancybox-group='gallery'>\n<img src='img/thumbs/$file/$entry' alt='' /></a>\n";
}
}
echo "</p>\n";
closedir($handle);
}
`
And advice would be wonderfully helpful. Thanks!
opendir should return true or false but it may not be playing nicely with the if statement Try this:
$handle = opendir('img/gallery/'.$file.'/');
if ($handle) {
Would also be good to var_dump out the $file value to make sure it is correct.
Surely you will need to nest the second while loop in the first if you are to iterate over each file in each folder...?
Did you try quotes for variables? I always quote out my variables, just good practice.
if ($handle = opendir('img/gallery/')) {
$blacklist = array('.', '..', 'somedir', 'somefile.php');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "<h2>$file</h2>\n";
}
}
closedir($handle);
}
echo "<P class='gallery'>\n";
if ($handle = opendir('img/gallery/' . $file . '/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a class='fancybox' href='img/gallery/" . $file . "/" . $entry . "' data-fancybox-group='gallery'>\n<img src='img/thumbs/" . $file . "/" . $entry . "' alt='' /></a>\n";
}
}
echo "</p>\n";
closedir($handle);
}
Related
I am trying to find a solution to remove files from a directory listing. I found an example that works bery well for files within the same directory. However I assume that I would need to change directories but I am not understanding how to accomplish this.
Here is the example that works for files in the current directory
<?php
if(isset($_GET['delete'])){
$delurl=$_GET['delete'];
unlink($delurl);
}
?>
<?php
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<br><b>$entry - Delete<br></b>";
}
}
closedir($handle);
}
?>
Ok got it.
<?php
if(isset($_GET['delete'])){
$delurl=$_GET['delete'];
unlink($delurl);
}
?>
<?php
if ($handle = opendir('../videos/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<br><b>$entry - Delete<br></b>";
}
}
closedir($handle);
}
?>
I just added the path after href=\?delete= and before $entry
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
I am trying to pull images simply from my directory /img and load them dynamically into the website into the following fashion.
<img src="plates/photo1.jpg">
That's it. It seems so simple but all of the code I have found basically doesn't work.
What I have that I am trying to make work is this:
<?php
$a=array();
if ($handle = opendir('plates')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/\.png$/", $file))
$a[]=$file;
else if(preg_match("/\.jpg$/", $file))
$a[]=$file;
else if(preg_match("/\.jpeg$/", $file))
$a[]=$file;
}
closedir($handle);
}
foreach($a as $i){
echo "<img src='".$i."' />";
}
?>
This can be done very easily using glob().
$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
print "<img src=\"plates/$file\" />";
You want your source to show up as plates/photo1.jpg, but when you do echo "<img src='".$i."' />"; you are only writing the file name. Try changing it to this:
<?php
$a = array();
$dir = 'plates';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
You should use Glob instead of opendir/closedir. It's much simpler.
I'm not exactly sure what you're trying to do, but you this might get you on the right track
<?php
foreach (glob("/plates/*") as $filename) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == "png") {
// do something
} elseif($path_parts['extension'] == "jpg") {
// do something else
}
}
?>
I created a script that list the directories in the current directory
<?php
$dir = getcwd();
if($handle = opendir($dir)){
while($file = readdir($handle)){
if(is_dir($file)){
echo "$file<br />";
}
}
?>
but the problem is, I am seeing this ".." and "." right above the directory listings, when someone clicks it, they get redirected one level up the directories.. can someone tell me how to remove those ".." and "." ?
If you use opendir/readdir/closedir functions, you have to check manually:
<?php
if ($handle = opendir($dir)) {
while ($file = readdir($handle)) {
if ($file === '.' || $file === '..' || !is_dir($file)) continue;
echo "$file<br />";
}
}
?>
If you want to use DirectoryIterator, there is isDot() method:
<?php
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isDot() || !$fileInfo->isDir()) continue;
$file = $fileinfo->getFilename();
echo "$file<br />";
}
?>
Note: I think that continue can simplify this kind of loops by reducing indentation level.
Or use glob:
foreach(glob('/path/*.*') as $file) {
printf('%s<br/>', $file, $file);
}
If your files don't follow the filename dot extension pattern, use
array_filter(glob('/path/*'), 'is_file')
to get an array of (non-hidden) filenames only.
Skips all hidden and "dot directories":
while($file = readdir($handle)){
if (substr($file, 0, 1) == '.') {
continue;
}
Skips dot directories:
while($file = readdir($handle)){
if ($file == '.' || $file == '..') {
continue;
}
<?php
if($handle = opendir($dir)){
while($file = readdir($handle)){
if(is_dir($file) && $file !== '.' && $file !== '..'){
echo "$file<br />";
}
}
}
?>
I am very much a beginner when it comes to using PHP. I was given this code, to try and output the contents of a files on a folder, onto a server, but my issue is I do not know how to read and alter this code to fit my specific file path. Can someone help me out with this, and lets just use the name folder as an arbitrary pathname.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
<?php
$dir_path = '.'; // '.' = current directory.
// '..' = parent directory.
// '/foo' = directory foo in the root file system
// 'folder' = a dir called 'folder' inside the current dir
// 'a/b' = folder 'b' inside 'a' inside the current dir
// '../a' = folder 'a' inside the parent directory
if ($handle = opendir($dir_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
<?php
$path = '.';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Detailed explanation and examples: http://www.php.net/function.opendir