Iam writting here for the first time. I wrote some php code which read files from folder and makes list of links to each file. Problem is that, its generates two more links at the begining of the list, which arent links to files, only dots. Does anyone have some idea to help me about this? This is the code:
<?php
echo '<h1>Download</h1>';
echo '<br/>';
echo '<div id="download">';
$dir = "images/download/";
if (is_dir($dir)) {
if($dh = opendir($dir)) {
while(($file = readdir($dh))!==false){
echo ''. str_replace("_"," ", trim($file,'.pdf, .pptx')) . "";
}
closedir($dh);
}
}
echo '</div>';
?>
You always have to check for the . and .. directories and ignore them. They exist in every folder.
They are what are used when you do cd .. and ls . for example in a command window
<?php
echo '<h1>Download</h1>';
echo '<br/>';
echo '<div id="download">';
$dir = "images/download/";
if (is_dir($dir)) {
if($dh = opendir($dir)) {
while(($file = readdir($dh))!==false){
if ( $file == '.' || $file == '..' ) {
continue;
}
echo ''. str_replace("_"," ", trim($file,'.pdf, .pptx')) . "";
}
closedir($dh);
}
echo '</div>';
?>
Related
<?php
$dir_path = "./folder/";
if(is_dir($dir_path))
{
$files = opendir($dir_path);
{
if($files)
{
while (($file_name = readdir($files)) !== FALSE)
{
if ($file_name != '.' && $file_name != '..'){
echo "".$file_name."<br>";
#echo "<img src=".$file_name.">";
}
}
}
}
}
?>
Returns an array of files and directories from the directory . ... I wanted to easely access data in a certain directory using foreach. I came up with the following:
but it is not download
it say like this
Object not found!
In these cases first you need get files of directory like following:
$dir = './FILE_FOLDER_NAME';
$files = scandir($dir);
unset($files[0]);
unset($files[1]);
Why we used unset, these code remove . and .. from $files variable and you have just file names.
Now you can show files with this approach:
foreach($files as $key => $value):
$path_info = pathinfo($value); //RETURN FILE EXTENTION
?>
<a href="DIRECTORY_PATH<?php echo $value; ?>" target="_blank"><?php echo $value; ?>
<?php
endforeach;
If you want to delete a file can add new button to your foreach like this:
<button href="PHPSAMPLEFILE.PHP?file=<?php echo base64_encode ($value); ?>"><?php echo 'DELETE'; ?></button>
and in your PHP file:
$file = base64_decode($_GET['file']);
$path = './DIRECTORY_PATH/'.$file;
unlink($path);
I have searched on google and on this site for something similar to what I want but nothing fits exactly and all my efforts to adapt them have failed, I want to make a script that will map out its directory and all its subfolders and the folders be at the top of the subdirectory and files after them. So far I have come up with this:
<?php
$rawParent = scandir('.');
$parentDir = array_diff($rawParent, array('.', '..','cgi-bin','error_log'));
$arrayOfDirectories = array();
$arrayOfFiles = array();
foreach ($parentDir as $child){
if(is_dir($child)){
array_push($arrayOfDirectories,$child);
}else{
array_push($arrayOfFiles,$child);
}
}
foreach ($arrayOfDirectories as $directory){
echo $directory.'<br>';
}
echo "<br>";
foreach ($arrayOfFiles as $file){
echo "<a href='".$file."'>".$file.'</a><br>';
}
?>
It's good so far but it only does the first level of the directory, can this code be adapted to go through all levels of folders and nest them? If so how? I need a few pointers, I will further use javascript to have toggles on the folders to see the contents, so I will need PHP to output something nested.
Sorry if I am not making much sense, don't really know how to explain.
Use recursive function like this :
<?php
function list_directory($directory)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
print '<ul>'.$directory.'/'.$file;
list_directory($directory.'/'.$file);
print '</ul>';
}
else
{
print "<li> $file </li>";
}
}
closedir($the_directory);
}
$path_to_search = '/var/www';
list_directory($path_to_search);
?>
Version with storage in array :
<?php
function list_directory($directory, &$storage)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
list_directory($directory.'/'.$file, $storage);
}
else
{
$storage[] = $file;
}
}
closedir($the_directory);
}
$storage = array();
$path_to_search = '/var/www';
list_directory($path_to_search, $storage);
echo '<pre>', print_r($storage,true) , '</pre>';
?>
This will do what you asked for, it only returns the sub directory names in a given path, and you can make hyperlinks and use them.
$yourStartingPath = "your string path";
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($yourStartingPath),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$path = strtoupper($file->getRealpath()) ;
$path2 = PHP_EOL;
$path3 = $path.$path2;
$result = end(explode('/', $path3));
echo "<br />". basename($result);
}
}
I need help on this one
I have managed to loop through my parent folder and echo the sub folder en wants to create on PHP file that can help me loop through the sub folders. my code is below:
<?php
$path="../downloads/pastpapers/UCU/foundations/";
$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
$dirName=$fileinfo->getFilename();
echo "<div id='linkFrame'><a href='$dirName.php'><img src='images/folder.png'><br/>$dirName</img></a> </div>";
}
}
?>
Just try the following in test file php :
<?php
$path = '../downloads/pastpapers/UCU/foundations';
ListFolder($path);
function ListFolder($path)
{
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$explode = explode("/", $path);
$dirname = end($explode);
//display the target folder.
echo ("<li>$dirname\n");
echo "<ul>\n";
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
ListFolder($path."/".$file);
}
else
{
//Display a list of files.
echo "<li>$file</li>";
}
}
}
echo "</ul>\n";
echo "</li>\n";
//closing the directory
closedir($dir_handle);
}
?>
for more information pls visit this page
I have the next code:
<?php
$path = 'imgsFor';
$files_array = scandir($path);
for ($x=0; $x<=4; $x++)
{
echo '<img src="imgsFor/$files_array[$x]" <br>';
}
?>
In order to display all images in the folder imgsFor.
For some reason, I see the just boxes and not the actual images.
What can be the reason?
The best way for me is to use glob function:
foreach (glob($path) as $filename) {
echo '<img src="' . $path . '/' . $filename . '"/><br/>';
}
You messed up some things. Your correct script would be
<?php
$path = 'imgsFor/';
$files_array = scandir($path);
foreach($files_array as $f) {
if(is_dir($path . $f) === false)
continue;
echo '<img src="' , $path , $f , '"><br>';
}
/* EOF */
The reason is that your URL is invalid. Your variable wont echo out if you use single quotes. You also forgot to end the tag. Try this:
echo "<img src='http://yourwebsite.com/imgsFor/{$files_array[$x]}'/><br/>";
Please check you directory path and use is_dir which returns false when the file doesn't exist. you can try like this
$path = 'imgsFor';
$scan = scandir($path);
foreach($scan as $file)
{
if (!is_dir($path))
{
echo $file.'\n';
}
}
I have this php code that works great, but the only thing is that images that are loaded from the folder are random, and I need them to load numerically by order.
`
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false)
{
if(substr( $file, -3 ) == "jpg" )
{
echo "<div class='container'><img class='lazy' id='background' src='../blogimg/loader.gif' data-original='../blogimg/luda_jesus/" . $file . "' width='884' height='587'></div>";
//echo "<br />";
}
}
closedir($dir);
?>`
Please help me
You can do this much more easily with glob:
$files = glob("../blogimg/luda_jesus/*.jpg");
natsort($files); // can also use other sort functions here, take your pick
foreach ($files as $file) {
echo '...';
}
I chose natsort as the sort function above because it will sort 2.jpg before 10.jpg, while plain sort will do the opposite. See comparison of array sorting functions for more information.
Assuming "numerically" means by filename, you can simply do you while loop and populate all files in an array, sort it, and then load the files.
Example:
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false) {
if(substr( $file, -3 ) == "jpg" ) {
$filelist[] = $file;
}
}
closedir($dir);
sort($filelist);
for($i=0; $i<count($filelist)-1; $i++) {
echo "<div class='container'>
<img class='lazy' id='background'
src='../blogimg/loader.gif'
data-original='../blogimg/luda_jesus/" . $file . "'
width='884' height='587'>
</div>";
}
If you require different means of sorting, please mention so.