Search code examples
phpfilepathopendir

What is the correct format for a directory path when using PHP's opendir()?


I'm having trouble with my filepath when using opendir(). I get the following warning:

PHP Warning: opendir(/uploads/users/405/images/profile/profilepic/) [function.opendir]: failed to open dir: No such file or directory in /home/my_folder/public_html/models/photos.php on line 1059

line 1059 in photos.php has the following:

if ( ( $handle = opendir( $profile_pic_path ) ) ) { // do stuff }

where:

$profile_pic_path = '/uploads/users/405/images/profile/profilepic/';

I've tried several different things, but I can't get it to work (I keep getting the PHP Warning message in my error log).

What am I doing wrong?


Solution

  • / in the begining of path means - absolute path.

    you should use absolute or relative path:

    $profile_pic_path = dirname(__FILE__).'/uploads/users/405/images/profile/profilepic/';
    

    or

    $profile_pic_path = 'uploads/users/405/images/profile/profilepic/';
    

    this works if your script in the same directory where uploads dir is.

    in case if your script in subdirectory (lib/tests/test.php for example), and you have no global $basepath initialised:

    $profile_pic_path = dirname(dirname(dirname(__FILE__)))
                        .'/uploads/users/405/images/profile/profilepic/';
    

    often somewhere in top of logic here is global or constant basedir used (say in config/main.php) :

    global $basedir=dirname(dirname((__FILE__));