PHP absolute path not working

1.4k views Asked by At

I have set up a simple virtual host.

JUST added these lines at the bottom

<VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot "/var/www/Reminder/"


    <Directory "/var/www/Reminder">
        AllowOverride all
        Require all granted
        php_admin_value open_basedir "/var/www/Reminder/"
    </Directory>



    php_admin_value open_basedir "/var/www/Reminder/" 
    ServerName test.mydomain.com
    ErrorLog "logs/yourdomain.com-error_log"
    CustomLog "logs/yourdomain.com-access_log" common
</VirtualHost>

What I basically want is, while including files in php from files inside the Reminder folder, if I give an absolute path , like "/test/" , it should consider the Reminder folder as the root, and search for a test folder from inside Reminder.

Right now, when I type echo DIR , I am shown /var/www/Reminder.

my file structure is:

/var/www/Reminder/database/db_connect.php /var/www/Reminder/registration/registration_handler.php

This is what my db_connect.php has :

<?php 

    define('DBHOST','localhost');
    define('DBUSER','root');
    define('DBPASS','password');
    define('DBNAME','Reminder');

    $conn=mysqli_connect(DBHOST,DBUSER,DBPASS) ;
    if(!$conn) { 

        echo mysqli_connect_error();

    }
    else {
        echo "connected successfully";
    }

?>

This is what my registration_handler has :

<?php
    echo "hi";
    echo __DIR__;
    require_once("/database/db_connect.php");

    mysqli_query($conn,"INSERT INTO users () VALUES ()") or die (mysqli_error($conn));
?>

I believe, if everything is fine, I should be able to get the "connected successfully" message (from db_connect) , if I run registration_handler.php , but thats not happening.

When i include the same file like this :require_once("../database/db_connect.php"); , i get the output

1

There are 1 answers

1
olav On

The open_basedir option only restricts what paths you are allowed to access from PHP code. It does not affect the way file lookups from inside your PHP code works.

This means that setting open_basedir to /var/www/Reminder/ will cause an error if you try to open for example /etc/passwd (because it is outside of the allowed the allowed directories). It will not transform an open of /etc/passwd into /var/www/Reminder/etc/passwd.

What you probably want instead is to use the __DIR__ constant in order to open by a relative path. For example, to load /var/www/Reminder/database/db_connect.php from /var/www/Reminder/registration/registration_handler.php, you would use something like:

$basedir = dirname(__DIR__);
require_once($basedir . '/database/db_connect.php');

We use dirname() to strip away the last path component from the end of __DIR__. I.e.:

  • __DIR__: /var/www/Reminder/registration
  • dirname(__DIR__): /var/www/Reminder