Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to get absolute path of file PHP

Tags:

php

Is there a way to get the absolute path of a file while having it included in another script?

So I'm trying to include a file that's in folder A while I'm in folder B but it keeps trying to refer to folder B's location.

I've tried dirname, $SERVER['PHP_SELF'], cwd(), but they still return a relative path.

like image 281
A. L Avatar asked Nov 03 '16 05:11

A. L


People also ask

How do I find the absolute path of a file?

Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).

How do I find the path of a file in PHP?

php $path = "C:\\test_folder\\folder2\\folder4"; $sub_folder = scandir($path); $num = count($sub_folder); for ($i = 2; $i < $num; $i++) { if(is_file($path. '\\'.

How can I get full image path in PHP?

If you mean the path where the image was located on the user computer before he/she uploaded it to your form - you can never know it in php or javascript or anywhere else. In PHP you can see the path on SERVER (usually in the temporary folder) where the file was stored so you can read or copy it.

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.


2 Answers

You can try like this

include dirname(__FILE__).'/../yourfile.php';

Since PHP 5.3.0 you can use also the magic constant __DIR__ More info in the docs

Another way is

$rootDir = realpath($_SERVER["DOCUMENT_ROOT"]);

include "$rootDir/yourfile.php";
like image 173
S.I. Avatar answered Sep 22 '22 13:09

S.I.


__FILE__

That is the absolute path to the file being executed.

simple usage examples:

echo __FILE__;

echo "This file is: " . __FILE__;

like image 33
WEBjuju Avatar answered Sep 20 '22 13:09

WEBjuju