Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

include_once(): failed to open stream: No such file or directory - PHP

I was trying to make a simple signup system in php. I have a class called Admin(inside controller folder) which extends the DBConnection.php class. Admin class have a signup method for letting adming signup but got problem there. Error occurs at 'include_once' and error says 'Warning: include_once(../Database/DBConnection.php): failed to open stream: No such file or directory in C:\xampp\htdocs\WoodlandsAway\controller\Admin.php on line 15----- ' 'Warning: include_once(): Failed opening '../Database/DBConnection.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\WoodlandsAway\controller\Admin.php on line 15----- ' 'Fatal error: Class 'DBConnection' not found in C:\xampp\htdocs\WoodlandsAway\controller\Admin.php on line 17'

here is my include_once code

include_once ('../Database/DBConnection.php');

And here is my folder structure

--DBConnection.php

class DBConnection {
//put your code here
private $host;
private $user;
private $pass;
private $database;
private $conn;

function DBConnection() {
    $this->host = 'localhost';
    $this->user = 'root';
    $this->pass = '';
    $this->database = 'woodlands_away';
}

public function getConnections() {
    $this->conn = new mysqli($this->host, $this->user, $this->pass, $this->database) or
    die($this->conn->error);

    return $this->conn;
}

}

And Admin.php

include_once ('../Database/DBConnection.php');

class Admin extends DBConnection {
public function Admin() {
    parent::DBConnection();
}

public function signup($username, $password) {
    $sql = "insert into users values(".$username.", ".$password.")";

    return $this->getConnections()->query($sql);
}}
like image 288
Nishan Dhungana Avatar asked Sep 02 '25 16:09

Nishan Dhungana


1 Answers

First, I suggest you to declare a constant that represents the root path of your project. This constant must be declared in a unique way such an index.php or similar, but in the root of your project:

define('PROJECT_ROOT_PATH', __DIR__);

Then your include call should looks like this:

include_once (PROJECT_ROOT_PATH . '/Database/DBConnection.php');

(Always specify the leading slash)

The problem is that currently your code may rely on the Working directory so you probably get an unexpected working directory.

like image 145
Geolim4 Avatar answered Sep 05 '25 06:09

Geolim4