devjs11
devjs11

Reputation: 1948

How to setup doc_root path for php files?

I am trying to call files or folders like:

require('/functions.php');
$a = '/folder/';

but it wont work and keeps giving error "failed to open stream", i know i could modify "doc_root" from php.ini but not sure if that would be right and what exactly to modify.

Anyone could suggest pls?

thank you.

------ UPDATE ----- I am just trying to create a file inside subfolders using fopen:

$ourFileName = "/folder/subfolder/index.php"
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

but i dont want to use $_SERVER['DOCUMENT_ROOT'] because i want to use the same variable $ourFileName for building links

------UPDATE------ To make it even more clear, here is the code that does not work:

<?php 
$ourFileName = '/jobs/';
$ourFileHandle = fopen($ourFileName.'index.php', 'w') or die("can't open file");
fwrite($ourFileHandle, 'hello world');  
fclose($ourFileHandle); 
?>

Upvotes: 1

Views: 7636

Answers (3)

RobertPitt
RobertPitt

Reputation: 57268

To get the best possible root path you should define a constant in your view file, i.e (index.php) and you should make it cross platform compatible.

after the years working in PHP and multi platform applications I discovered the best method to do this is a combination of the following native PHP Functions and constants:

  • define
  • str_replace
  • dirname
  • __FILE__

Heres why we use the functions:

  • The reason why we use define is to allow the document root to stay within the global scope
  • The reason for str_replace is to change the slashes to be cross platform compatible
  • The reason for dirname is to help the relative path to the root view file
  • The reason for __FILE__ is to discover the view file for dirname

We could use __DIR__ for PHP5 but __FILE__ is better as it would support previous versions of windows.

Fully combined you would have a valid relative path to your view file.

define("ROOT_PATH",str_repalce("\\","/",dirname(__FILE__)));

this would produce the perfect relative path to your index directory without the trailing slash, you should then include your files like so:

require_once ROOT_PATH . "/system/classes/some.class.php";

In windows both / and \ are valid, and for other operating systems its just /, so generally you should always build your applications with the / as your directory separator.

Upvotes: 3

Kyle Wild
Kyle Wild

Reputation: 8915

Unless your functions.php file is in the linux system root, that path will not work, as the first / character means "all the way to root".

If functions.php is in the same directory as your quoted file, try this:

$dir = dirname(__FILE__);
$functions_absolute_path = $dir . '/functions.php';
require($functions_absolute_path);

Upvotes: 0

user557846
user557846

Reputation:

how about using : $_SERVER["DOCUMENT_ROOT"]

Upvotes: 4

Related Questions