i want to split a files name in to two for accessing it through a loop using php
eg ; image_apple.jpg, image_mango.jpg , image_grapes.jpg etc
and there is a description file correspomding to each image files
eg: description_apple.txt
all these files are in same folder .
i want to show all images and thire curresponding description file in ma web page
someone pls help me
thanks in advance
You could use something like this:
<?php
$files = scandir("./"); //./ is the current directory
foreach($files as $file) {
$info = explode('_', $file); //Split on _
//Skip all files withouth description
if (count($info) <= 1) {
continue;
}
$info = explode('.', $info['1']); //Split on .
//Is there a file with description info?
if (file_exists('description_' . $info['0'] . '.txt')) {
$description = file_get_contents('description_' . $info['0'] . '.txt'); //$description contains the file description
}
}
?>
try this
if ($handle = opendir('/folder path here/')) {
while (false !== ($entry = readdir($handle))) {
$names=explode("_",pathinfo($entry)['filename']);
echo " desc: description_".$names[0].".txt";echo " name: image_".$names[1].".jpg";
echo "<br>";
}
closedir($handle);
}
Related
I have one main directory "Images" and many subdirectories - inside them are files (in main folder too). Example tree:
+Images
-first.jpg
-second.jpg
++FOLDER1
--image1.jpg
++FOLDER2
--image2.jpg
I found a script there:
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
return $files;
}
}
$list = ListFiles('../upload/_thumbs/Images');
sort($list);
foreach ($list as $key=>$file){
echo '<option value="">'.$file.'</option>';
}
This script works fine but I can sort my results by folders (first main content, then rest)... I get i my select:
../upload/_thumbs/Images/first.jpg
../upload/_thumbs/Images/FOLDER1/image1.jpg
../upload/_thumbs/Images/FOLDER2/image2.jpg
../upload/_thumbs/Images/second.jpg
Expection:
../upload/_thumbs/Images/first.jpg
../upload/_thumbs/Images/second.jpg
../upload/_thumbs/Images/FOLDER1/image1.jpg
../upload/_thumbs/Images/FOLDER2/image2.jpg
I would be glad if you will help me! Thanks!
Well it probably has something to do with the sort function you call somewhere in the last lines
sort($list);
It's causing the array to sort alphabetical. You could try to leave it out, or you could try to use natsort.
natsort($list);
This is happening because you are sorting with the full path. Instead of sort, I would use uasort which is similar to sort, except you use a callback function to define which goes first.
alternatively, you could get by prepending the file name to the path and using the key on insert. In other words:
array_push($files, $dir . "/" . $file);
becomes:
$files[$file . $dir] = $dir . "/" . $file;
then you sort using ksort
i have a folder with some folder names, for example 3 folders:
2012-2013, 2013-2014 ,2014-2015
is any way with some php code, to show the names folders in my php like this:
<option value="2012-2013">2012-2013</option>
<option value="2013-2014">2013-2014</option>
<option value="2014-2015">2014-2015</option>
untill I use to show the stuff with php-foreach using a html-template inside the folders.
but i want to show direct the stuff without using the template in the data-folder, is any way? thx.
I suppose you want to recursive the folder in a directory. Below please find the code.
<?php
$folder_name = "c:\\your_folder\\";
$folders = scandir($folder_name);
echo '<select>';
foreach($folders as $folder){
if (is_dir($folder_name . $folder)){
if ($folder != '.' && $folder != '..')
echo '<option value="' . $folder . '">' . $folder . '</option>';
}
}
echo '</select>';
?>
You need to read the directory and print an option tag for each time you find a file that is a folder.
first thing you need to open file handler to your directory by giving the main folder path, than itterate over the directory by using the read method on the folder handler.
By using the "is_dir" function you can determine if the file is a folder, and if so print the file.
I added my solution which is recursive.
function printFolders($path = "", $c = 0) {
if ( empty($path) || !is_dir($path) )
{
return false;
}
//Folder handler
$handler = dir($path);
//Read each file name inside the directory
while(($file = $handler->read()) !== false)
{
// "." is the current folder and ".." is the parent folder
// We skip those folders
if ( $file == "." || $file == ".." )
{
continue;
}
// The current file path
$filePath = $path . "/" . $file;
if ( is_dir($filePath) )
{
//Just to make things more pretty
for($i=0; $i<=$c; $i++) {echo "-";}
//Printing the folder name
echo $file . "<br>";
//Calling the function again with the folder we found
printFolders($filePath, $c+1);
}
}
}
printFolders("path/to/folder");
This is actually is an easy task
I want to display contents of all files located in specified folder.
I am passing directory name
echo "<a href='see.php?qname=". $_name ."'>" . $row["qname"] . "</a>";
on second page ,
I am iterating over the directory content
while($entryname = readdir($myDirectory))
{
if(is_dir($entryname))
{
continue;
}
if($entryname=="." || $entryname==".." )
{}
else
{
if(!is_dir($entryname))
{
$fileHandle=fopen($entryname, "r");
while (!feof($fileHandle) ) {
$line = fgets($fileHandle);
echo $line . "<br />";
}
.
.
.
but I am unable to read any file , I have changed their permissions as well.
I tried putting directory name statically which worked,
Can someone suggest what am I doing wrong?
$entryname will contain JUST the filename, with no path information. You have to manually rebuild the path yourself. e.g.
$dh = opendir('/path/you/want/to/read/');
while($file = readdir($dh)) {
$contents = file_get_contents('/path/you/want/to/read/' . $file);
^^^^^^^^^^^^^^^^^^^^^^^^^^---include path here
}
Without the explicit path in your "read the file code", you're trying to open and read a file in the script's current working directory, not the director you're reading the filenames from.
Much simpler:
foreach(glob("$myDirectory/*") as $file) {
foreach(file($file) as $line) {
echo $line . "<br />";
}
}
Even simpler:
foreach(glob("$myDirectory/*") as $file) {
echo nl2br(file_get_contents($file));
}
The code below is able list down nicely all the folders, sub folder and their files.
But I need create this in as a directory.html which will hyperlink to the file. it will be open at a computer so the linking how do I do it, as of now I only can display the content but no hyperlink.
Thanks for helping. !
<?php
$base_dir = 'C:\Users\baoky\Dropbox\SS133A\FINAL PHASE\Documents To Submit';
if (is_dir($base_dir))
scan_directory($base_dir);
else
echo 'Invalid base directory. Please check your setting.';
// recursive function to check all dir
function scan_directory($path) {
if (is_dir($path)) {
if ($dir_handle = opendir($path)) {
echo '<ul>';
while (($file = readdir($dir_handle)) !== false) {
if ($file != '.' && $file != '..') {
if (is_dir($path . '/' . $file)) {
echo '<li>';
echo ''.$file.'';
scan_directory($path . '/' . $file);
echo '</li>';
}
else
echo "<li>{$file}</li>";
}
}
echo '</ul>';
}
}
}
?>
the issue is with the recursive is not able to get the full path. I did a href but if a folder is inside 1 folder, then in another sub folder , then another sub folder which is folder1/folder2/folder3/file.txt then its display only file.txt which is wrong.
echo "<a href='$file'>$file</a>" will be the basics of it, though you'd need to build the FULL path leading up the file, since you're doing a recursive dump and only dealing with the "local" sub-path.
I have a basic PHP script that displays the file contents of a directory. Here is the script:
<?php
$Dept = "deptTemplate";
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'docs';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
} else {
echo '``'.$file_or_dir."\n`` - [Delete button/link]`<br/>`";
}
}
closedir($handle);
}
?>
I am trying to create a delete link/button that displays next to each file and when clicked, the corresponding file will be deleted. Would you know how to do this?
Use the built-in unlink($filepath) function.
Sure, you'd have to use unlink() and rmdir(), and you'd need a recursive directory removal function because rmdir() doesn't work on directories with files in them. You'd also want to make sure that the deletion script is really secure to stop people from just deleting everything.
Something like this for the recursive function:
function Remove_Dir($dir)
{
$error = array();
if(is_dir($dir))
{
$files = scandir($dir); //scandir() returns an array of all files/directories in the directory
foreach($files as $file)
{
$fullpath = $dir . "/" . $file;
if($file == '..' || $file == '.')
{
continue; //Skip if ".." or "."
}
elseif(is_dir($fullpath))
{
Remove_Dir($fullpath); //recursively remove nested directories if directory
}
elseif(is_file($fullpath))
{
unlink($fullpath); //Delete file otherwise
}
else
{
$error[] = 'Error on ' . $fullpath . '. Not Directory or File.' //Should be impossible error, because everything in a directory should be a file or directory, or . or .., and thus should be covered.
}
}
$files = scandir($dir); //Check directory again
if(count($files) > 2) //if $files contains more than . and ..
{
Remove_Dir($dir);
}
else
{
rmdir($dir); //Remove directory once all files/directories are removed from within it.
}
if(count($error) != 0)
{return $error;}
else
{return true;}
}
}
Then you just need to pass the file or directory to be deleted through GET or something to the script, probably require urlencode() or something for that, make sure that it's an authorized user with permissions to delete trying to delete the stuff, and unlink() if it's a file, and Remove_Dir() if it's a directory.
You should have to prepend the full path to the directory or file to the directory/file in the script before removing the directory/file.
Some things you'll want for security is firstly making sure that the deletion is taking place in the place it's supposed to, so someone can't do ?dir=/ or something and attempt to delete the entire filesystem from root, which can probably be circumvented by prepending the appropriate path onto the input with something like $dir = '/home/user/public_html/directories/' . $_GET['dir'];, of course then they can potentially delete everything in that path, which means that you need to make sure that the user is authorized to do so.
Need to keep periodic backups of files just in case.
Something like this? Not tested...
<?php
echo '`'.$file_or_dir.' - [Delete button/link]<br/>`';
?>
<?php
if ($_GET['del'] == 1 && isset($_GET['file_or_dir']){
unlink ("path/".$_GET['file_or_dir']);
}
?>
I've worked it out:
I added this delete link on the end of each listed file in the original script:
- < a href="delete.php?file='.$file_or_dir.'&dir=' . $dir . '"> Delete< /a>< br/>';
This link takes me to the download script page, which looked like this:
<?php
ob_start();
$file = $_GET["file"];
$getDir = $_GET["dir"];
$dir = 'docs/' . $getDir . '';
$isFile = ($dir == "") ? 'docs/' . $file . '' : '' . $dir . '/' . $file . '';
if (is_file($isFile)){
if ($dir == "")
unlink('docs/' . $file . '');
else
unlink('' . $dir . '/' . $file . '');
echo '' . $file . ' deleted';
echo ' from ' . $dir . '';
}
else{
rmdir('' . $dir . '/' . $file . '');
echo '' . $dir . '/' . $file . ' deleted';}
header("Location: indexer.php?p=" . $getDir . "");
ob_flush();
?>
It all works brilliantly now, thank you all for your help and suggestions :)