Skip to content

relative path in require_once doesn't work

The require_once function in PHP is used to include a specific PHP file in another file, but it will only include the file once to prevent multiple declarations.

When using a relative path with require_once, it is important to understand that the path is relative to the file that is using the require_once statement, not the file that is being executed.

If you are having trouble getting a relative path to work with require_once, make sure that the path is correct and that the file you are trying to include exists in the specified location. If the file is in a different directory, you may need to use a relative path that goes up one or more directories (e.g. ../) in order to reach the correct location.

In addition, it's always a good practice to use the absolute path instead of relative path, this will help you to avoid the path problem. Using the __DIR__ magic constant ensures the path is resolved relative to the current file's location:

php
// Directory structure:
// /var/www/html/index.php
// /var/www/html/includes/config.php

// In index.php:
require_once __DIR__ . '/includes/config.php';

Also if you are using a virtual host and using a different base directory make sure that the path is relative to the actual file system layout rather than the URL structure.

You may also check the permissions of the file and the folder that you're trying to access, to ensure that the PHP process has read access to them.

Dual-run preview — compare with live Symfony routes.