Home » Php » file – php include_once path

file – php include_once path

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to find a way to make the include_once(); path start from the beginning directory and then find the path e.g. instead of ../../../path/to/file I would have /path/to/file. If I do do that /path/to/file it says no such file or directory, here is my direct code

<?php
include_once("/assets/page_assets.php");
?>
How to&Answers:

If you have an Apache server

<?php
include_once($_SERVER['DOCUMENT_ROOT'] . "/assets/page_assets.php");
?>

"/assets/page_assets.php" means from the root of the disk, not from the root folder of the server. If you are talking about some other beginning directory then define physical path (path in the file system of the server, not the web path) to it as a separate constant/variable and prepend it to the included path as shown above.

Answer:

You can specify include path explicitly:

<?php ini_set('include_path',ini_get('include_path').':../../../:');  ?>

But as Cheery mentioned in comment, you must include your file without leading slash:

<?php
include_once("assets/page_assets.php");
?>

Answer:

To do this you must use the path from the root. In some cases this might look like /var/www/mysite.com/assets/page_assets.php. One way to find that path is to use __FILE__ (That’s 2 underscores both in front and behind). If you echo that from a file, it will show you the complete path. You should be able to use that to set the correct full path.

Answer:

Start your script with chdir($_SERVER['DOCUMENT_ROOT']);

Now you can call include("path/to/file.php"); and it will start looking from the webroot.