a little question. I have this code, which is works perfect for files, but If am trying search on a directory name, the result is blank. How I can fix that?
<?php
function listdirs($dir,$search)
{
static $alldirs = array();
$dirs = glob($dir."*");
foreach ($dirs as $d){
if(is_file($d)){
$filename = pathinfo($d);
if(eregi($search,$filename['filename'])){
print "". $d . "<br/>";
}
}else{
listdirs($d."/",$search);
}
}
}
$path = "somedir/";
$search= "test";
listdirs($path,$search);
?>
somedir/test/
result: blank (I want: /somedir/test/)
somedir/test/test.txt
result: OK
I want to search also in the directory names, how I can do that?
If you want to search for a directory, you're going to have to change the if(is_file($d)) block. Right now, you're having it simply call listdirs again when it encounters a directory... but this also means you'll never see a print with a link to said directory.
I suggest doing something like this in the foreach instead:
$filename = basename($d);
if(eregi($search,$filename)){
print "". $d . "<br/>";
}
if(is_dir($d)){
listdirs($d."/",$search);
}
Your script is working fine. I think the webserver user does not have permissions to the given directory.
Related
I'm currently setting up a search engine and has been experiencing some weird stuff with this loop, and it seams like it doesn't go through all the 200 000 files.
I can see the file on the server, but when I search for it, it doesn't show up. Other searches, it works just fine.
The folders it's searching through have another layer of folders, and all the files are only stored on the last layer of folders. so I'm searching like this:
glob('database/*/*/*.txt')
Here is my code:
if (isset($_GET['q'])){
$search = $_GET['q'];
}else{die;}
$files = array();
foreach (glob('database/*/*/*.txt', GLOB_NOCHECK) as $path) {
$title = basename($path, ".txt").PHP_EOL;
if(strripos($title,$search) != false){
array_push( $files, $path );
echo $title . '<br>';
echo $path . '<br>';
}
}
Error log shows nothing and access log gives 200 response.
Is it any other ways to search files in folders? or is it something that I'm not seeing?
As I understand it - all your titles are fetched into the foreach-loop, but they are not included in the array $files. Therefore it would make sense to dig into the if statement:
if(strripos($title,$search) != false){
The manual from php.net states:
Warning This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Because you should use === to check equal state, you should use !== (and not !=) to state not equal. Therefore the first thing I would test would be:
if(strripos($title,$search) !== false){
If it's still the same issue I would try to remove PHP_EOL from the line:
$title = basename($path, ".txt").PHP_EOL;
and have it like this instead:
$title = basename($path, ".txt");
I'm not sure why you're are using PHP_EOL here, but I don't think it is necessary? (not sure though - someone - tell me if I'm wrong).
So the code that would be left is this:
foreach (glob('database/*/*/*.txt', GLOB_NOCHECK) as $path) {
$title = basename($path, ".txt");
if(strripos($title,$search) !== false){
array_push( $files, $path );
echo $title . '<br>';
echo $path . '<br>';
}
}
A while ago I made a post (Searching for a specific string from all PHP files in the parent directory) that was about me finding the position of the file path in an array, only if the file had a specific keyword.
However, that was in my old website, which I have now lost. So I am currently recreating it. However, for some reason this function does not work.
public function build_active_theme() {
$dir = CONPATH . '/themes/' . $this->get_active_theme() . '/';
$theme_files = array();
foreach(glob($dir . '*.php') as $file) {
$theme_files[] = $file;
}
$count = null;
foreach($theme_files as $file) {
$file_contents = file_get_contents($file);
if(strpos($file_contents, 'Main')) {
$array_pos = $count;
$main_file = $theme_files[$array_pos];
echo $main_file;
}
$count++;
}
}
This function causes the following error:
Notice: Undefined index: in /home/u841326920/public_html/includes/class.themes.php on line 30
I have narrowed the problem down the something wrong with the $count variable. Whenever I try and echo the $count value once the script has found the correct file, nothing is shown.
But after spending nearly an hour on such a simple problem, it is obviously starting to frustrate me, so I am now seeking help.
(Note: I directly copied the function directly from the old post into my code, and made the appropriate changes to variables to 'work' in the new site, so it's is pretty much exactly the same as the solution that fixed my previous problem - which funnily enough was also caused by the $count variable).
Thanks,
Kieron
You can use the foreach $key instead of a separate count variable, try the code below:
foreach($theme_files as $key => $file) {
$file_contents = file_get_contents($file);
if(strpos($file_contents, 'Main') !== false) {
$main_file = $theme_files[$key];
echo $main_file;
}
}
You are setting
$count = null;
, try to ++ it before the
$array_pos = $count;
I am trying to copy a file that I download it. The file name is test1234.txt, but I want to access it using a wildcard like this: test*.txt and after that to move it to another folder (because I don't know how the file name looks like, but I know that the beginning is test and the rest is changing every time I download a new one). I tried some codes:
$myFile = 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNewFile = 'C:/Users/Carl/Downloads/'. date("y-m-d").'/text.xml';
if(preg_match("([0-9]+)", $myFile)) {
echo 'ok';
copy($myFile, $myNewFile);
}
I am getting an error because of * in $myFile. Any help is very appreciated.
$myFile= 'C:/Users/Carl/Downloads/'. date("y-m-d") . '/test*.txt';
$myNyFile = 'C:/Users/Carl/Downloads/'.date("y-m-d").'/test.txt';
foreach (glob($myFile) as $fileName) {
copy($fileName, $myNyFile);
}
For complete response, if you want to only move *.txt in NewFolder.
$myFiles = 'C:/Users/Carl/Downloads/*.txt';
$myFolderDest = 'C:/Users/Carl/NewFolder/';
foreach (glob($myFiles) as $file) {
copy($file, $myFolderDest . basename($file));
}
I have a folder on my server called /assets/includes/updates/ with .php files inside featuring static html content.
I'd like to randomly grab a file from this folder and echo it into a div. Here is what I have:
<?php
function random_update($dir = $_SERVER['DOCUMENT_ROOT'].'/assets/includes/updates/')
{
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
?>
<div class="my-div">
<?php echo random_update(); ?>
</div><!--end my-div-->
I am getting 500 errors? Also, my intention is to only echo 1 file at a time. Will the provided code accomplish that?
Php does not recognize the syntax you used. You have to bypass it like this:
<?php
function random_update($dir = NULL)
{
if ($dir === NULL) {
$dir = $_SERVER['DOCUMENT_ROOT'] . '/assets/includes/updates/';
}
$files = glob($dir . '/*.*');
$file = array_rand($files);
return $files[$file];
}
Also, you might want to enable error dumping in your development environment so you know what went wrong next time.
Aside from another answers spotted issues, for your code to do what you want, you have to replace your following code:
<?php echo random_update(); ?>
for this one:
<?php echo file_get_contents (random_update()); ?>
because your current code will print the filename inside the div, while I think you wanted the actual content of the file to be inserted in the div.
You can't use any expression as "default" function's argument value.
$value can = a folder structure to the language file. Example: languages/english.php
$value can also = the files name. Example: english.php
So I need to get the current folder that $value is in and delete the folder ONLY if there are no other files/folders within that directory (after deleting the actual file as I am doing already, ofcourse).
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
#unlink($module_path . '/' . $value);
// Now I need to delete the folder ONLY if there are no other directories inside the folder where it is currently at.
// And ONLY if there are NO OTHER files within that folder also.
}
}
How can I do this?? And wondering if this can be done without using a while loop, since a while loop within a foreach loop could take some time, and need this to be as quick as possible.
And just FYI, the $module_path should never be deleted. So if $value = english.php, it should never delete the $module_path. Ofcourse, there will always be another file in there, so checking for this is not necessary, but won't hurt either way.
Thanks guys :)
EDIT
Ok, now I'm using this code here and it is NOT working, it is not removing the folders or the files, and I don't get any errors either... so not sure what the problem is here:
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
if (#unlink($module_path . '/' . $value))
#rmdir(dirname($module_path . '/' . $value));
}
}
NEVERMIND, this works a CHARM!!! Cheers Everyone!!
The easyest way is try to use rmdir. This don't delete folder if it is not empty
rmdir($module_path);
also you can check is folder empty by
if(count(glob($module_path.'*'))<3)//delete
2 for . and ..
UPD: as I reviewed maybe you should replace $module_path by dirname($module_path.'.'.$value);
Since the directory you care about might be part of the $value, you need to use dirname to figure out what the parent directory is, you can't just assume that it's $module_path.
$file_path = $module_path . '/' . $value;
if (#unlink($file_path)) {
#rmdir(dirname($file_path));
}
if (is_file($value)) {
unlink($value);
} else if (is_dir($value)) {
if (count(scandir($value)) == 2) }
unlink($value)
}
}
http://php.net/manual/en/function.is-dir.php
http://www.php.net/manual/en/function.scandir.php
The code below will take a path, check if it is a file (i.e. not a directory). If it is a file, it will extract the directory name, then delete the file, then iterate over the dir and count the files in it, if the files are zero it'll delete the dir.
Code is as an example and should work, however privileges and environment setup may result in it not working.
<?php
if(!is_dir ( string $filename )){ //if it is a file
$fileDir = dirname ( $filename );
if ($handle = opendir($fileDir)) {
echo "Directory handle: $handle\n";
echo "Files:\n";
$numFiles=0;
//delete the file
unlink($myFile);
//Loop the dir and count the file in it
while (false !== ($file = readdir($handle))) {
$numFiles = $numFiles + 1;
}
if($numFiles == 0) {
//delete the dir
rmdir($fileDir);
}
closedir($handle);
}
}
?>