PHP glob function from another directory - php

I have some PDF files in public_html/site.com/pdf but in my index files is located in public_html/site.com/
I would like to use the glob() function to iterate through all the pdf files located In the pdf/ folder. The problem is that I am not getting any result.
Here is that I tried.
# public_html/index.php
<?php
foreach (glob("pdf/*.pdf") as $filename) {
echo "$filename <br/>";
}
?>

Alternatively, if you want to search your public folder recursively, you can use RecursiveDirectoryIterator to achieve this: Consider this example:
Lets say you have this directory structure:
/var/
/www/
/test/
/images/
image.png
/files/
/files2/
pdf.pdf <-- searching for some pdf files, happens to be here
<?php
$filetype_to_search = 'pdf';
$root_path = '/var/www/test'; // your doc root (or maybe C:/xampp/htdocs/) :p
foreach ($iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root_path,
RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST) as $value) {
if($value->getExtension() == $filetype_to_search) {
echo $value->getPathname() . "<br/>";
}
}
// ouput should be /var/www/test/images/files/files2/pdf.pdf
?>

My advice? Just set your full path as a variable & use it in cases like this.
In general you really cannot trust automatic methods used to get paths to be reliable for various reasons. This is why I have decided it’s best to set a base path explicitly as I explain here. I will assume you are on a standard Linux setup with /var/www/ as the root. So in your case you would set:
$BASE_PATH = '/var/www/public_html/site.com/';
And then your final code would be something like this:
$BASE_PATH = '/var/www/public_html/site.com/'
foreach (glob($BASE_PATH . "pdf/*.pdf") as $filename) {
echo "$filename <br/>";
}

Related

Mentioning directory together with glob

I have this script to access all the xml files in a folder.
But how would I specify a directory inside the glob ?
Here's my code :-
foreach (glob("*.xml*") as $filename) {
echo $filename."<br />";
}
You can add the directory in this way :-
$dir="dirname/";
foreach (glob("$dir*.xml*") as $filename) {
echo $filename."<br />";
}
Notice :- When you echo the filename, the directory would come attached to it. So for instance the filename is example.txt, then the output will be dirname/output.txt. You can then use explode to remoe the dir name.

php mkdir folder tree from array

I'm trying to create a folder tree from an array, taken from a string.
$folders = str_split(564);
564 can actually be any number. The goal is to create a folder structure like /5/6/4
I've managed to create all folders in a single location, using code inspired from another thread -
for ($i=0;$i<count($folders);$i++) {
for ($j=0;$j<count($folders[$i]);$j++) {
$path .= $folders[$i][$j] . "/";
mkdir("$path");
}
unset($path);
}
but this way I get all folders in the same containing path.
Furthermore, how can I create these folders in a specific location on disk? Not that familiar with advanced php, sorry :(
Thank you.
This is pretty simple.
Do a for each loop through the folder array and create a string which appends on each loop the next sub-folder:
<?php
$folders = str_split(564);
$pathToCreateFolder = '';
foreach($folders as $folder) {
$pathToCreateFolder .= DIRECTORY_SEPARATOR . $folder;
mkdir($folder);
}
You may also add the base path, where the folders should be created to initial $pathToCreateFolder.
Here you'll find a demo: http://codepad.org/aUerytTd
Or you do it as Michael mentioned in comments, with just one line:
mkdir(implode(DIRECTORY_SEPARATOR, $folders), 0777, TRUE);
The TRUE flag allows mkdir to create folders recursivley. And the implode put the directory parts together like 5/6/4. The DIRECTORY_SEPARATOR is a PHP constant for the slash (/) on unix machines or backslash (\) on windows.
Why not just do:
<?php
$directories = str_split(564);
$path = implode(DIRECTORY_SEPARATOR, $directories);
mkdir($path, 0777, true);
Don't know what you're really trying to do, but here are some hints.
There are recursive mkdir:
if(!file_exists($dir)) // check if directory is not created
{
#mkdir($dir, 0755, true); // create it recursively
}
Path you want can be made in two function calls and prefixed by some start path:
$path = 'some/path/to/cache';
$cache_node_id = 4515;
$path = $path.'/'.join('/', str_split($cache_node_id));
Resulting path can be used to create folder with the code above
So here we come to a pair of functions/methods
function getPath($node_id, $path = 'default_path')
{
return $path.'/'.join('/', str_split($node_id))
}
function createPath($node_id, $path = 'default_path');
{
$path = getPath($node_id, $path);
if(!file_exists($path)) // check if directory is not created
{
#mkdir($path, 0755, true); // create it recursively
}
}
With these you can easily create such folders everywhere you desire and get them by your number.
As mentioned earlier, the solution I got from a friend was
$folders = str_split(564);
mkdir(implode('/',$folders),0777,true);
Also, to add a location defined in a variable, I used
$folders = str_split($idimg);
mkdir($path_defined_earlier. implode('/',$folders),0777,true);
So thanks for all the answers, seems like this was the correct way to handle this.
Now the issue is that I need to the created path, so how can I store it in a variable? Sorry if this breaches any rules, if I need to create a new thread I'll do it...

Find path to file on server using php -

I would like to know how to get the absolute file path of the file i have found using glob() function. I am able to find a desired file using
foreach (glob("access.php") as $filename) {
echo "$filename absolutepath is: ";
}
not sure what function gets the full path of the file searched. Tried to google but can't find anything sensible.
Thanks
Slight update :
I have noticed that glob() function only searches the directory that the script is run from - and that is not good to me. I need a function that is equivalent to unix find / -name "somename"
Any alternative ? or am i missing something with the glob() ??
If you have to look also for files in subdirectories, you could use something like the following:
foreach (glob("{access.php,{*/,*/*/,*/*/*/}access.php}", GLOB_BRACE) as $filename) {
echo "$filename absolutepath is: ".realpath($filename);
}
You can use realpath to get file absolute path. More info: http://www.php.net/manual/en/function.realpath.php
I thinkt you need realpath(), as described here: http://www.php.net/manual/en/function.realpath.php
foreach (glob("access.php") as $filename) {
echo "$filename absolutepath is: " . realpath($filename);
}
The directory in which the glob function searches is available through the getcwd function.
To search any directory, given its path, one may use the following code snippet:
$dirToList = '/home/username/documents';
$patternToSearch = '*.odt'; // e.g. search for LibreOffice OpenDocument files
$foundFiles = FALSE;
$olddir = getcwd();
if (chdir($dirToList)) {
$foundFiles = glob($patternToSearch);
chdir($olddir); // switch back to the dir the code was running in before
if ($foundFiles) {
foreach ($foundFiles as $filename) {
echo nl2br(htmlentities(
'found file: '.$dirToList.DIRECTORY_SEPARATOR.$filename."\n"
, ENT_COMPAT, 'UTF-8'));
}
}
// else echo 'no found files';
}
// else echo 'chdir error';
To finally satiesfy your wish to do a search like
find / -name "somename"
you may put that code snippet in a function and call it while iterating through the directory tree of interest using PHP's RecursiveDirectoryIterator class.

Having troubling listing subdirectories recursively in PHP

I have the following code snippet. I'm trying to list all the files in a directory and make them available for users to download. This script works fine with directories that don't have sub-directories, but if I wanted to get the files in a sub-directory, it doesn't work. It only lists the directory name. I'm not sure why the is_dir is failing on me... I'm a bit baffled on that. I'm sure that there is a better way to list all the files recursively, so I'm open to any suggestions!
function getLinks ($folderName, $folderID) {
$fileArray = array();
foreach (new DirectoryIterator(<some base directory> . $folderName) as $file) {
//if its not "." or ".." continue
if (!$file->isDot()) {
if (is_dir($file)) {
$tempArray = getLinks($file . "/", $folderID);
array_merge($fileArray, $tempArray);
} else {
$fileName = $file->getFilename();
$url = getDownloadLink($folderID, $fileName);
$fileArray[] = $url;
}
}
}
Instead of using DirectoryIterator, you can use RecursiveDirectoryIterator, which provides functionality for iterating over a file structure recursively. Example from documentation:
$path = realpath('/etc');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
echo "$name\n";
}
This prints a list of all files and
directories under $path (including
$path ifself). If you want to omit
directories, remove the
RecursiveIteratorIterator::SELF_FIRST
part.
You should use RecursiveDirectoryIterator, but you might also want to consider using the Finder component from Symfony2. It allows for easy on the fly filtering (by size, date, ..), including dirs or files, excluding dirs or dot-files, etc. Look at the docblocks inside the Finder.php file for instructions.

Foreach glob to include files in a subdirectory

I'm trying to learn how to include all the files in a directory using glob(), however I can't seem to get it to work. This is the code I have now:
foreach (glob("addons/*.php") as $filename) {
include $filename;
}
However a single file include seems to work just fine:
include "addons/hello.php";
This is what my file structure looks like:
Theme
-addons
--hello.php
-index.php
-options.php
So I'm not sure where the problem is. The code is inside a (theme) subdirectory itself, if that makes a difference at all. Thanks.
Use this for testing:
foreach (glob("addons/*.php", GLOB_NOCHECK) as $filename) {
PRINT $filename . "\n";
}
Should the directory not exist relatively to the current, then it will show addons/*.php as output.
This recursive function should do the trick:
function recursiveGlob($dir, $ext) {
$globFiles = glob("$dir/*.$ext");
$globDirs = glob("$dir/*", GLOB_ONLYDIR);
foreach ($globDirs as $dir) {
recursiveGlob($dir, $ext);
}
foreach ($globFiles as $file) {
include $file;
}
}
Usage: recursiveGlob('C:\Some\Dir', 'php');
If you want it to do other things to the individual file, just replace the include $file part.
Include is going to be using the search path which (while it typically includes the current working directory) isn't limited to that... using glob() with a relative directory path will always be relative to the current working directory. Before you enter your loop... ensure that your current working directory is where you think it is using echo getcwd()... you may find you're not in the Theme subdirectory after all; but that the Theme subdirectory is in the search path.
Make sure that path to file is absolute (from root of your server).
In my case this example works without problems:
$dir = getcwd();//can be replaced with your local path
foreach (glob("{$dir}/addons/*.php") as $filename) {
if(file_exists($filename))
{
//file exists, we can include it
include $filename;
}
else
{
echo 'File ' . $filename . ' not found<br />';
}
};

Categories