2

I'm trying to reach files available in a folder available in root directory. I'm using

foreach ( glob( dirname(__FILE__) . '/MobileApp/Images/*' ) as $filename) 

but am unable to go up multiple levels in the directory. How can i do this?

My folder structure is as follow:

File where the glob() is being called from : root/MobileApp/Portal/SystemFiles/file.php

File I'm trying to reach is in root/MobileApp/Images/*

Any help is much appreciated.

bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72
Saeed Joul
  • 244
  • 2
  • 15
  • 1
    Why cant you? are there PHP errors? sorry your question isn't very clear as to what is preventing you from directory reading. – Scuzzy Jul 17 '19 at 21:21
  • How does the directory structure look like and what directory are you trying to fetch files from? What do you mean by go up multiple levels? – bestprogrammerintheworld Jul 17 '19 at 21:23
  • It seems that you are using a slash at the beginning IE `/root/MobileApp/ ... ` -- As far as `php` is concerned .. . This would start at the **Operating System Root** -- If this is the case .. try using the *full* path IE `/home/root/MobileApp/Whatever ...` – Zak Jul 17 '19 at 21:25
  • @Scuzzy im trying to get the subfolders in that directory to populate a select form. but all i get is empty list. When i move my php file to root directory and use '/MobileApp/Images/*' it works perfectly. – Saeed Joul Jul 17 '19 at 21:25
  • @bestprogrammerintheworld the MobileApp file is right on root directory. the file.php is in MobileApp/Portal/FileSystems – Saeed Joul Jul 17 '19 at 21:29
  • 2
    `dirname( dirname( __DIR__ ) ) . DIRECTORY_SEPARATOR . 'Images' . DIRECTORY_SEPARATOR . '*'` should get you to the images folder from the context of your starting `SystemFiles` path then you can use something like https://stackoverflow.com/questions/17160696/php-glob-scan-in-subfolders-for-a-file to get all files in subfolders if needed. I'd much prefer you define a [constant](https://www.php.net/manual/en/language.constants.php) that is the full path to your images folder rather than trying to work it out relative to the scripts location. – Scuzzy Jul 17 '19 at 21:29
  • @Scuzzy you are a genius !! worked like a charm. Thank you. If you want to post it as answer so i can tick it :) – Saeed Joul Jul 17 '19 at 21:33

1 Answers1

1

If all you are trying to do is locate the Images folder relative to your current folder you can use either:

dirname( dirname( __DIR__ ) ) . DIRECTORY_SEPARATOR . 'Images' . DIRECTORY_SEPARATOR . '*'

-or-

dirname( dirname( dirname( __FILE__ ) ) ) . DIRECTORY_SEPARATOR . 'Images' . DIRECTORY_SEPARATOR . '*'

another solution is to define constants that configure your important application paths. https://www.php.net/manual/en/function.define.php

define( 'PATH_IMAGES', '/full/path/to/folder' );

and then you can use PATH_IMAGES anywhere in your application

Scuzzy
  • 12,186
  • 1
  • 46
  • 46