How to access correctly classes from directories/subdirectories?

Viewed 37

When I try to access includes/config.php from inside account/index.php I get these errors:

Warning: include(classes/user.php): failed to open stream: No such file or directory in /var/www/htdocs/dashboard/includes/config.php on line 6

Warning: include(): Failed opening 'classes/user.php' for inclusion (include_path='.:/usr/share/php') in /var/www/htdocs/dashboard/includes/config.php on line 6

I define the path correctly, but when index.php access to config.php, I think config.php occurs directory problem when calling classes in config.php, I couldn't find how to solve it.

Thanks in advance.

Here is folder structure

App/
├─ account/
│  ├─ index.php
├─ classes
├─ includes/
│  ├─ config.php
├─ index.php

index.php in account/index.php

<?php
require('../includes/config.php');
?>

config.php in includes/config.php

<?php
ob_start();
session_start();

//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
include('classes/slug.php');
$user = new User($db);
?>
2 Answers

As @Sohrab said you need to give it the absolute path. You can solve this problem with __DIR__. (the directory of the file) to learn more about DIR

You should use it like:

require(__DIR__.'/../includes/config.php');

also in config.php and other files:

include(__DIR__.'/../classes/user.php');
include(__DIR__.'/../classes/phpmailer/mail.php');
include(__DIR__.'/../classes/slug.php');

Config file looks for the files in its directory. You should change your code to:

<?php
ob_start();
session_start();

//include the user class, pass in the database connection
include('../classes/user.php');
include('../classes/phpmailer/mail.php');
include('../classes/slug.php');
$user = new User($db);
?>
Related