Can't get scandir to scan root directory - php

I've tried every path I can think of.
''
'/'
'htdocs/'
No matter what I try, I cant figure out how to scan the root directory.
So, how do you do it?
Current Code:
function pathing(){
$files = scandir('/');
foreach ($files as $file) {
if ($file === '.' OR $file === '..') {
} else {
print_r($file . ' ');
}
}
}

I'm moving my comment to an answer in order to bring attention to the solution for others who stumble across this question.
The directory root location is accessible in the $_SERVER array.
$_SERVER['DOCUMENT_ROOT']

Related

PHP GAE readdir() doesn't work as intended

I'm trying to recursively list every file that is in my bucket. It's not too many files but I'd like to list them to test a few things. This code works on a normal file system but it's not working on Google Cloud Storage.
Anyone have any suggestions?
function recurse_look($src) {
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_look($src . '/' . $file);
}
else {
echo $src . '/' . $file;
echo "<br />";
}
}
}
closedir($dir);
}
recurse_look("gs://<BUCKET>");
Personally, I would recommend not using a filesystem-impersonation abstraction layer on top of Google Cloud Storage, for a task such as listing everything inside a bucket -- rather, just reach out for the underlying functionality.
In particular, see https://cloud.google.com/storage/docs/json_api/v1/json-api-php-samples for everything about authentication etc, and, once, that's taken care of, focus on just one line in the example:
$objects = $storageService->objects->listObjects(DEFAULT_BUCKET);
This is all you need to list all objects in a bucket (which is not the same thing as "files in a directory", and the "filesystem simulations" on top of buckets and objects, I offer as being just my personal opinion, end up hurting rather than helping despite their excellent intentions:-).
Now if the objects' names contain e.g slashes and you want to take that into account as symbolically signifying something or other, go right ahead, but at least this way you're sure you're getting all the objects actually existing in the bucket, and, nothing but those!-)
Now that glob is working, you can try something like this
function lstree($dir) {
foreach (glob($dir . '/*') as $path) {
if (is_dir($path)) {
echo $path;
lstree($path);
} else {
echo $path;
}
}
lstree('gs://{bucket}/');

Warning: opendir(): The system cannot find the file specified. (code: 2)

I'm trying to turn the files in my 'objects' directory into an array, then use them to load the objects. But, for some reason, I continue to get this error
Warning: opendir(C:\xampp\htdocs/objects,C:\xampp\htdocs/objects): The system cannot find the file specified. (code: 2)
here is the code:
public function loadObjects(){
$files = array();
if ($handle = opendir(APP_PATH . 'objects'))
{
while (false !== ($entry = readdir($handle)))
{
if ($entry != "." && $entry != "..")
{
$files[] = $entry;
}
}
}
closedir($handle);
if(is_array($files) && count($files) > 0)
{
foreach($files as $value)
{
require_once(APP_PATH . 'objects/' . $value);
$value = stristr($value, '.', true);
self::$objects[$value] = new $object(self::$instance);
}
}
}
I know this is an old question but for any future viewers I will post an anwser just in case.
This type of error usually comes from a simple oversight. When developing most aplication the developer usualy uses a path like
http://localhost/myAppHome
or
http://96.82.102.233/myAppHome(if on remote server)
In this perticular case the APP_PATH is probably defined somethig like that:
define('APP_PATH',$_SERVER['DOCUMENT_ROOT']);
This will be wrong in every case when the app is being developed outside of a domain name.
$_SERVER['DOCUMENT_ROOT'] will resolve to the root of domain which in this case will be
http://localhost or http://96.82.102.233
The main directory for localhost or the IP address is going to be the diretory root of the server itself => drive:/xampp/htdocs (for example)
Basically to avoid this issue you should always mind not to ask for 'DOCUMENT_ROOT' when developing without a domain pointing to you app.
If you dont require reqular deploys you can just add the missing folder to the definition like so :
define('APP_PATH',$_SERVER['DOCUMENT_ROOT'].'/myAppHome');
In case you deploy on reqular basis and you are afraid you will forget to rever this change before depoying you can always insert an IF when defing APP_PATH like:
if($_SERVER['SERVER_NAME']=='localhost'){
define('APP_PATH', $_SERVER['DOCUMENT_ROOT'].'/myAppHome');
}else{
define('APP_PATH', $_SERVER['DOCUMENT_ROOT']);
}
You are trying to open that directory with a "/".
Try to replace:
C:\xampp\htdocs/objects
to
C:\xampp\htdocs\objects
Please be sure APP_PATH variable is not null and correct values. There is no scandir function usage on your codes.
After that, i suggest you to use DirectoryIterator.
http://www.php.net/manual/en/class.directoryiterator.php
Complete example:
http://fabien.potencier.org/article/43/find-your-files
APP_HOST = DIR folder;
APP_PATH = APP_PATH + DIR folder;
Example = "C:/xampp/htdocs" + "/parent/child/index.php"
if ($_SERVER['SERVER_NAME'] == "localhost") {
define('APP_HOST', pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME));
define('APP_PATH', $_SERVER['DOCUMENT_ROOT'] . APP_HOST);
} else {
define('APP_PATH', $_SERVER['DOCUMENT_ROOT']);
}

How to loop through parent directories in php?

There are all these resources for recursively looping through sub directories, but I haven't found ONE that shows how to do the opposite.
This is what I want to do...
<?php
// get the current working directory
// start a loop
// check if a certain file exists in the current directory
// if not, set current directory as parent directory
// end loop
So, in other words, I'm searching for a VERY specific file in the current directory, if it doesn't exist there, check it's parent, then it's parent, etc.
Everything I've tried just feels ugly to me. Hopefully someone has an elegant solution to this.
Thanks!
Try to create a recursive function like this
function getSomeFile($path) {
if(file_exists($path) {
return file_get_contents($path);
}
else {
return getSomeFile("../" . $path);
}
}
The easiest way to do this would be using ../ this will move you to the folder above. You can then get a file/folder list for that directory. Don't forget that if you check children of the directory above you then you're checking your siblings. If you just want to go straight up the tree then you can simply keep stepping up a directory until you hit root or as far as you are permitted to go.
<?php
$dir = '.';
while ($dir != '/'){
if (file_exists($dir.'/'. $filename)) {
echo 'found it!';
break;
} else {
echo 'Changing directory' . "\n";
$dir = chdir('..');
}
}
?>
Modified mavili 's code:
function findParentDirWithFile( $file = false ) {
if ( empty($file) ) { return false; }
$dir = '.';
while ($dir != '/') {
if (file_exists($dir.'/'. $file)) {
echo 'found it!';
return $dir . '/' . $file;
break;
} else {
echo 'Changing directory' . "\n";
chdir('..');
$dir = getcwd();
}
}
}

List files and subfolders from database in PHP

Beginner : I cant seem to get my head around the logic of it. Have searched but seems to come up with listing files and folders from an actual directory ie. (opendir).
My problem is :
Im trying to work out (in PHP) how to list files and subfolders from a path stored in a database. (Without any access to the file or dir, so just from the path name)
For example database shows:
main/home/television.jpg
main/home/sofa.jpg
main/home/bedroom/bed.jpg
main/home/bedroom/lamp.jpg
So if i specify main/home - it shows: television.jpg, sofa.jpg and the name of the subfolder : bedroom.
scanFolder('main/home');
function scanFolder($dir) {
foreach (scandir($dir) as $file) {
if (!in_array($file, array('.', '..'))) {
if (is_dir($file)) {
scanFolder($dir . '/' . $file);
}
else {
echo $dir . '/' . $file . "\n";
}
}
}
}
You would probably want to check on each iteration if the filename is a directory or not. If it is, open it up and read its contents and output them. A recursive function would work best in this situation.
http://php.net/manual/en/function.is-dir.php

PHP / Windows - Opendir() fails opening subdirectories within symbolic linked directories

Does anyone know a solution to this problem? I'm unable to open a subdirectory within a symboliclink'd directory. I've confirmed that the paths are correct (even copy & pasted the path into explorer, which parsed it fine). This is a strange, annoying, bug :|.
Example:
C:\folder\symbolic_link\dir1\dir2 - opening dir2 fails.
C:\folder\symbolic_link\dir1 - works
C:\folder\real_directory\dir1\dir2 - works
C:\folder\real_directory\dir1 - works
Alright, I finally found a hack to solve this bug in php's handling of symlinks on windows. The bug occurs when recursively iterating through files/directories using opendir(). If a symlink to a directory exists in the current directory, opendir() will fail to read the directories in the directory symlink. It is caused by something funky in php's statcache, and can be resolved by calling clearstatcache() before calling opendir() on the directory symlink (also, the parent directory's file-handle must be closed).
Here is an example of the fix:
<?php
class Filesystem
{
public static function files($path, $stats = FALSE)
{
clearstatcache();
$ret = array();
$handle = opendir($path);
$files = array();
// Store files in directory, subdirectories can't be read until current handle is closed & statcache cleared.
while (FALSE !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
$files[] = $file;
}
}
// Handle _must_ be closed before statcache is cleared, cache from open handles won't be cleared!
closedir($handle);
foreach ($files as $file)
{
clearstatcache($path);
if (is_dir($path . '/' . $file))
{
$dir_files = self::files($path . '/' . $file);
foreach ($dir_files as $dir_file)
{
$ret[] = $file . '/' . $dir_file;
}
}
else if (is_file($path . '/' . $file))
{
$ret[] = $file;
}
}
return $ret;
}
}
var_dump(filessystem::files('c:\\some_path'));
Edit: It seems that clearstatcache($path) must be called before any file-handling functions on the symlink'd dir. Php isn't caching symlink'd dirs properly.

Categories