Reputation: 449
I want to include a class that has been made to the php file, here I am using .htaccess. but once put into a php file, the php class can not be opened or loaded in a php file. The following directory structure in my web.
htdocs/
mysite/
src/
App/
Login.php <-- class file php
public/
login.php <-- file php
this is login class (mysite/src/App/Login.php)
class Login {
private $username;
//etc...
}
this is login file (mysite/public/login.php)
require('../src/App/Login.php');
$login = new Login();
this is .htaccess file (mysite/.htaccess)
Options +FollowSymLinks
RewriteEngine On
# skip for existing files/directories (/assets will be skipped here)
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# for public directory
rewritecond %{REQUEST_URI} !^/public/(.*)
RewriteRule .* index.php [L]
and index.php for rule in .htaccess file (mysite/index.php)
$requested = empty($_SERVER['REQUEST_URI']) ? false : $_SERVER['REQUEST_URI'];
$server_name = str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
switch ($requested) {
case $server_name:
include 'public/index.php';
break;
case $server_name.'login':
include 'public/login.php';
break;
default:
include 'public/404.php';
}
but when I open localhost/mysite/login there is an error
Warning: require(../src/App/Login.php): failed to open stream: No such file or directory in C:\xampp\htdocs\mysite\public\login.php on line ...
Fatal error: require(): Failed opening required '../src/App/Login.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\mysite\public\login.php on line ...
Can you help me?
thank you
Upvotes: 0
Views: 874
Reputation: 164766
A simple rule for including files via a relative path where you have not configured an application level include_path
; always base the relative path from that of the current script, eg
// public/login.php
require_once __DIR__ . '/../src/App/Login.php';
Because you're including public/login.php
from index.php
, the include path includes the parent directory of index.php
, ie mysite
. This applies across any files included.
When public/login.php
tries to include ../src/App/Login.php
it is actually attempting to open htdocs/mysite/../src/App/Login.php
.
Another thing you might want to try is configure an application level include path. For example, in index.php
...
set_include_path(implode(PATH_SEPARATOR, [
__DIR__ . '/src/App',
get_include_path()
]));
Now your src/App
directory is the first searched when performing an include
or require
so you can simply run
require_once 'Login.php';
An even better solution would be to register an autoloader, for example (in index.php
)
spl_autoload_register(function($class) {
require_once sprintf('%s/src/App/%s.php', __DIR__, $class);
});
Then you can simple create your class without worrying about including the file...
$login = new Login();
Upvotes: 1