Skip to content
Advertisement

How to solve the fatal error in require_once

My project has two entry point

JavaScript

for example

File 1:/index.php ( first entry point) – here we include the config form the config folder

JavaScript

File 2:service/service.php – here we include the config form the config folde

JavaScript

if i call the File 2:service/service.php has no fatal error

but when i call the File 1:/index.php it became the fatal error as failed to require ‘service/service.php’ because it require again and config path is invalid

How to solve this issue.

Advertisement

Answer

Reason:

This issue arises because your execution starts from index.php and then you require service/service.php. Now in service.php when you do ../config/config.php, PHP tries to resolve the directory path from index.php point of view and it doesn’t find any such file or directory. Hence, the error.

Solution:

Declare a constant in index.php. Check if this constant exists in service/service.php. If not, then require it, else skip it like below:

index.php:

JavaScript

service.php:

JavaScript

Note: It is always better to use __DIR__ giving absolute paths than relative paths to avoid such issues.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement