ajax php check how many folder i had in path src - php

<?php
header("content-type: application/json");
$files = array();
$dir = "Img/House"; //folder src path
$dirHandle = opendir($dir);
while(($file = readdir($dirHandle) !== false)){
if ($file !== "." && $file !== "..")
{
$files[] = $file;
}
}
echo($files);
//echo json_encode($directoryfiles);
?>
I am using ajax to php to return how many folder I had inside that src path , I can count the folder number on ajax , but something wrong with my php file , it seem wont check how many folder I have.
My intention is to use ajax and php check how many folder i have and push those name into the array $files. Can anyone help me take a look. I have no experience one this.

If you only want to return the number of directories in the given path, you can easily use count and glob, see below
// this is not needed unless you output json
// header("content-type: application/json");
$dir = "Img/House"; //folder src path
$dirs = glob($dir . "/*",GLOB_ONLYDIR);
print count($dirs);
// or directly
// print count(glob($dir . "/*",GLOB_ONLYDIR));
// if glob returns the current and parent dirs, "." and ".."
// just remove 2 from the count
// test by doing
print_r($dirs);
// then
print $count($dirs)-2;

Related

How to delete file in PHP

I want to delete files in a specific directory in PHP. How can I achieve this?
I have the following code but it does not delete the files.
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
I think your question isn't specific, this code must clear all files in the directory 'files'.
But there are some errors in that code I think, and here is the right code:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
And finally make sure that you provided the right path to dir().
You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.
$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files
// Check if file
if (is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove files matching a pattern like .png or .jpg, you have to use
$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);
See manual for glob.

Match string to a filename from folder using php

Hi I wonder if it is possible to match a string to a file from folder using php.
For example I have a folder called uploads and inside, I have different files like image1.png, image2.jpg, doc1.doc, and doc2.pdf.
Assuming I have this code on my php file:
<?php
$string = "image2";
// I need some function to display the image2 on my webpage.
// If string "image2" is found in the uploads folder
// then it should display the image
?>
Thanks!
I think this one should do what you want
$dir = "uploads";//the path to your folder
if(file_exists($dir)){
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file)) {
if ($file == "image2"){
// your code
}
}
}
}
}

how can i return the names of files in a directory using php

lets say I have a folder on a webhost that is called sebis_files and this folder contains some files, maybe pictures, docs...
I want to return the contents of this folder on a separate page, something like:
$row = get dir host/sebis_files*//everything
for ( $row !== 0){ //for every valid file
echo $row . "<br/>"; //return name of file
}
You can use opendir and readdir. Here's a breakdown:
We use __DIR__ to make the path relative to the directory of the current script, just to be safe:
$dir = __DIR__ . '/sebis_files';
Next we open the directory to read it's entries.
We call readdir, which will return a 'resource' object, or false if $dir is not a readable directory:
if ($dh = opendir($dir))
{
The directory is successfully opened.
We now call readdir on that directory. We use the return value of opendir, the mysterious 'resource' object, that will let PHP know what directory we are reading.
Every time we call readdir it will give us the next entry in the directory. When there are no more entries, readdir will return false:
while ( ($entry = readdir($dh)) !== false)
{
We have read a directory $entry: the name of a file or sub-directory inside $dir. So, it's not a full pathname. Let's print it's name, along with whether it is a directory or a file. We will use is_file and is_dir, but we will need to pass the full pathname (hence "$dir/$entry"):
if ( is_dir( "$dir/$entry" ) )
echo "Directory: $entry<br/>";
else if ( is_file( "$dir/entry" ) )
echo "File: $entry<br/>";
}
we are done with the directory, let's close it to free the resource:
closedir($dh);
}
But what if $dir cannot be opened for reading? Let's print a warning:
else
echo "<div class='warning'>cannot open directory!</div>";
you need is to see this
<?php
$dir = "/tmp";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
sort($files);
print_r($files);
rsort($files);
print_r($files);
?>
You can do it using the glob function :
$dir = "/your/dir/";
if(file_exists($dir))
{
foreach (glob("$dir*") as $file)
{
if(is_file($file))
{
echo basename($file) . "<br />";
}
}
}

Read only pdf files and get the filename of that pdf files in a directory

I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here

display images from multi directories

I want to display images from multi derctories.
I have this main folder ( backgrounds ) and inside this DIR I have 45 folders each folder have between 10-20 images.
I want to display all the images from the directories.
regards
Al3in
Try this one instead:
<?php
// Recursivly search through a directory and sub-directories for all
// image files. The returned result will be an array will all matches
// and their path (relative to the path sent in through the $dir argument)
//
// $dir - Directory to search through
// $filetypes - Array of file extensions to match
//
// Returns: Array() of files that match the $filetypes filter (or standard
// image file extensions by default).
//
function recursiveFileSearch($dir = '.', $filetypes = null)
{
if (!is_dir($dir))
return Array();
// create a regex filter so we only grab image files
if (is_null($filetypes))
$filetypes = Array('jpg','jpeg','gif','png');
$fileFilter = '/\.('.implode('|',$filetypes).')$/i';
// build a results array
$images = Array();
// open the directory and begin searching
if (($dHandle = opendir($dir)) !== false)
{
// iterate all files
while (($file = readdir($dHandle)) !== false)
{
// we don't want the . or .. directory aliases
if ($file == '.' || $file == '..')
continue;
// compile the path for reference
$path = $dir . DIRECTORY_SEPARATOR . $file;
// is it a directory? if so, append the results
if (is_dir($path))
$results = array_merge($results, recursiveFileSearch($path,$filetypes));
// must be a file, see if it matches our patter and add it if necessary
else if (is_file($path) && preg_match($fileFilter,$file))
$results[] = str_replace(DIRECTORY_SEPARATOR,'/',$path);
}
// close the directory when we're through
closedir($dHandle);
}
// return the outcome
return $results;
}
?>
<html><body><?php array_map(create_function('$i','echo "<img src=\"{$i}\" alt=\"{$i}\" /><br />";'),recursiveFileSearch('backgrounds')); ?></body></html>

Categories